How to avoid repetition of a column value in My-Sql - php

This is my result screenshot
I need to avoid repetition of the field Total, but I need all those data in all other fields, can anyone please help to attain the result!?
Here is my SQL Query
SELECT
(SELECT SUM(credit.amount)
FROM credit,customers
WHEREcredit.date BETWEEN '2018-05-01' AND '2018-05-31'
AND credit.cus_id=customers.id) AS Total,
credit.amount, credit.date,
customers.name
FROM customers, credit
WHERE credit.date BETWEEN' 2018-05-01' AND '2018-05-31'
AND credit.cus_id=customers.id
ORDER BY credit.date

You can add a row counter and use it with a conditional function IF. If the row number is <=1 it runs the subquery otherwise it prints an empty varchar ''.
As I said in the comment, I will consider to extract the subquery and run it in a separate query, then add its result to the first row with the application.
SET #rank=0;
SELECT #rank:=#rank+1 AS rank,
IF(#rank>1,'',(SELECT SUM(credit.amount)
FROM credit,customers
WHEREcredit.date BETWEEN '2018-05-01' AND '2018-05-31'
AND credit.cus_id=customers.id)) AS Total,
credit.amount, credit.date,
customers.name
FROM customers, credit
WHERE credit.date BETWEEN' 2018-05-01' AND '2018-05-31'
AND credit.cus_id=customers.id
ORDER BY credit.date

Related

Get Last Payment From A User in SQL

I have this table
I am trying to get the sum of principal + interest from the last transaction date. Column 4. is the last transaction performed - [No column name] is the transaction date
What I have tried so far:
select sum(h.principal+h.interest) as amt_paid, MAX(h.trx_date)
from Loanhist h WHERE h.ac_no = '$id' and h.trx_type='LP'
GROUP BY principal, interest
The test data generation is for Oracle, but you should easily be able to adapt it. The actual query will work on SQL server. You'll need to use an approach like this if the account can post more than one transaction in a day. Otherwise the 'LIMIT/TOP 1' approaches in the other answers will work fine.
CREATE GLOBAL TEMPORARY TABLE balances
( ac_no CHAR(100),
principal FLOAT,
interest FLOAT,
tranDate DATE
)
ON COMMIT PRESERVE ROWS;
INSERT INTO balances VALUES (1,123.123,.456,DATE '2017-01-01');
INSERT INTO balances VALUES (1,100,.456,DATE '2017-01-02');
INSERT INTO balances VALUES (1,200,.1,DATE '2017-01-02');
INSERT INTO balances VALUES (2,200,.1,DATE '2017-01-02');
INSERT INTO balances VALUES (2,300,.1,DATE '2017-01-02');
SELECT SUM
( CASE WHEN tranDate = max_tran_date
THEN principal + interest
ELSE 0
END
) AS tranSum
FROM (SELECT sub.*,
MAX(tranDate) OVER() AS max_tran_date
FROM balances sub
) BAL;
Your question is not really clear. But if you just want to get the last transaction performed by the user, the best thing to do will be to rely on IDs instead of dates.
SELECT TOP 1 * FROM Loanhist h WHERE h.trx_type='LP' ORDER BY h.ac_no DESC
try to use LIMIT keyword.For Example, Select * from table name where condition LIMIT 1.It will return first row
Try this:
SELECT TOP 1 sum(h.principal+h.interest) as amt_paid, h.trx_date
FROM Loanhist h WHERE h.ac_no = '$id' AND h.trx_type='LP'
ORDER BY h.ac_no DESC;

MYSQL count rows instead of showing results

So I have the following query, which I use it to get some analytics stats.
SELECT count(*) as total,CONCAT(YEAR(created),'-',MONTH(created),'-',DAY(created))
as date_only FROM logs where action = 'banner view'
and created BETWEEN '2015-07-03 21:03'
AND '2017-08-02 21:03' group by date_only order by created asc
This works, and it gives me this:
So what I actually need is, the total count of the rows in this case is 20, this is a dummy example, but I need to use this count to check before showing the stats if the data is too big to be displayed on a graphic.
Can this be achieved?
//LE
So the process will be like this:
1. Get a count of the total rows, if the count of rows is smaller than X(number will be in config and it will be a basic if statement), then go ahread and run the above query.
More info:
I actually use this query to display the stats, I just need to adapt it in order to show the total count rows
So the result of thquery should be
total | 20 in this case
I think you would want to use a derived table. Just wrap your original query in parenthesis after the FROM and then give the derived table an alias (in this case tmp). Like so:
SELECT count(*) FROM (
SELECT count(*) as total,CONCAT(YEAR(created),'-',MONTH(created),'-',DAY(created))
as date_only FROM logs where action = 'banner view'
and created BETWEEN '2015-07-03 21:03'
AND '2017-08-02 21:03' group by date_only order by created asc
) as tmp;
If I understand what you want to do correctly, this should work. It should return the actual number of results from your original query.
What's happening is that the results of the parenthesized query are getting used as a sort of virtual table to query against. The parenthesized query returns 20 rows, so the "virtual" table has 20 rows. The outer count(*) just counts how many rows there are in that virtual table.
Based on the PHP tag, I assume you are using PHP to send the queries to MySQL. If so, you can use mysqli_num_rows to get the answer.
If your query result is in $result then:
$total = mysqli_num_rows($result);
Slightly different syntax for Object Oriented style instead of procedural style.
The best part is you don't need an extra query. You perform the original query and get mysqli_num_rows as an extra without running another query. So you can figure out pagination or font size or whatever and then display without doing the query again.
This is an small query but works fine, and give me the total number of rows, you just need add your conditions.
SELECT COUNT(*) FROM table WHERE field LIKE '%condition%'
The group by I think you need to eliminated, becouse, this instead of count the records, divide in all your group by, example: records = 4, with group by you have
1
1
1
1
I hope this help you
You can try this way .
SELECT COUNT(*) FROM ( SELECT count(*) as total,CONCAT(YEAR(created),'-',MONTH(created),'-',DAY(created))
as date_only FROM logs where action = 'banner view'
and created BETWEEN '2015-07-03 21:03'
AND '2017-08-02 21:03' group by date_only HAVING total >=20 ) temp

How to reduce subquery execution time...?

I want per day sales item count so for that one i already created query but it takes to much around 55.585s and query is
Query :
SELECT
td.db_date,
(
select count(*) from order as order where DATE(order.created_on) = td.db_date
)as day_contribute
FROM time_dimension as td
So can any one please let me know how may i optimized this query and reduce execution time.?
You can modify your query to join like:
SELECT
td.db_date, count(order.id) as day_contribute
FROM time_dimension as td
LEFT JOIN order ON DATE(order.created_on) = td.db_date
GROUP BY td.db_date;
I do not know your primary id key for table order - so used just "order.id". Replace it with your.
Also it is very important - test if you have index on td.db_date field.
And one more important thing - better to avoid using DATE(order.created_on). Because it is mean that DATE() method will be called each time when DB will compare dates. If it is possible - convert order.created_on to same format as td.db_date. Or join by other fields. That will add speed too.
First you should make sure you have index on created_on column in order table.
However if you have many records in time_dimension and many records in order table it might be hard to optimize the query, because for each record from time_dimension you need to search in order table.
You can also change count(*) into count(order_id) (assuming primary key in order table is order_id) or add extra column with date only in order table (created_on_date with date only and index on this column) so your query could look like this:
SELECT
td.db_date,
(
select count(order_id) from order where order.created_on_date = td.db_date
)as day_contribute
FROM time_dimension as td
However it's possible the execution time might be too high if you have many records in both tables, so it might be necessary to create one extra table where you hold number of orders for each day and update it in cron or when adding/updating/deleting records in order table

UNION mysql determine which table the result came from

$stmt = $dbh->prepare("SELECT id FROM table1 UNION SELECT id FROM table2 UNION SELECT id FROM table3 ORDER BY id DESC LIMIT 1");
The code above is my code for auto generating ID. I want to select the last inserted ID. What I want to do is I want to get the last ID inserted on three tables. It can be from any of the three tables. And then i want to increment that ID. But the catch is i need to know which table the last ID is from so i can select another field and record that the last ID has a certain attribute. This attribute is depending on the table that is why i want to get the table.
Add a discriminator column, and use the MAX aggregate function for each query to avoid sorting a huge intermediate resultset, and use UNION ALL set operator in place of UNION operator. (Since each query will return only one row, that's not going to make much of a difference; but where we don't need to eliminate duplicate rows, we prefer the UNION ALL set operator to avoid the unnecessary (and sometimes expensive) operation.
Something like this should return the result you seem to be after:
( SELECT 'table1' AS source
, MAX(t1.id) AS max_id
FROM table1 t1
)
UNION ALL
( SELECT 'table2' AS source
, MAX(t2.id) AS max_id
FROM table2 t2
)
UNION ALL
( SELECT 'table3' AS source
, MAX(t3.id) AS max_id
FROM table3 t3
)
ORDER BY max_id DESC
LIMIT 1
That will give you a resultset that identifies the table name that had the maximum id.
NOTE: This assumes that the "last inserted id" is identified by the maximum value. If two tables have the same maximum id value, it's indeterminate which row will be returned. You can add source to the ORDER BY to make it deterministic:
ORDER BY max_id DESC, source DESC
(The actual requirements aren't clear to me; the statement above should return the same value that was being returned by the query in the question, along with a discriminator which tells which table the id value is from.)
Reference: https://dev.mysql.com/doc/refman/5.5/en/union.html
NOTE: This may satisfy your use case, but in the more general case, we advise avoiding this approach to get the id value of the row that was last inserted.
For values of an auto_increment column, where the value is automatically assigned, the last_insert_id function will return the id value of the first row that was inserted by the immediately preceding INSERT statement in the same session. In a multiuser system, it is not safe to assume that the "highest" id value was a row inserted by the current session - that approach is effectively broken.
Try to get last inserted ID of all three tables and with inserted time then differentiate based on inserted time

Php Mysql sum total with select all rows returned

How can i query and return all the rows but with "SUM" added to my query?
Here is my sample query:
select SUM(amount) as total, user_id, username, from table where user_cat = '1';
if I remove SUM, I get the correct number of rows returned, but when I add SUM, the row result is decreased.
Any Idea how to do this?
You have noticed it's impossible to make the query in the way you tried as SUM() aggregates the other rows and only one row is displayed. One way to solve this is to separate SUM() in a subquery as described below:
select n.total,
user_id,
username
from table,
(select SUM(amount) as total
from table
where user_cat = '1') n
where user_cat = '1';
I prefer to make this in two separate queries. Now you'll have to deal with the first column and make it invisible. If you use two queries you'll have to deal with the second query. The choice is yours.

Categories