Home > Net >  GROUP BY user id and day in mysql
GROUP BY user id and day in mysql

Time:06-28

I have this table:

"SELECT id, DATE_FORMAT(date, '%d/%m/%y %H:%i') AS date, name, id_user, total_amount FROM CAJA"

I need to GROUP by id_user and DAY, to show only the users with debt, so I have this query:

$st = $conn->prepare("SELECT id, DATE_FORMAT(date, '%d/%m/%y %H:%i') AS date, name, id_user, total_amount FROM CAJA WHERE active != 0 GROUP BY id_user, date ORDER BY id DESC");
$st->execute();
while($row = $st->fetch(PDO::FETCH_ASSOC)) { ....

But show me the results separated in the same day, I need to group all the user receipt per day (because each user can have more than one receipt every day), per example:

337 26/06/22 15:39  JOHN DOE1 // same user  
333 26/06/22 13:12  JOHN DOE1 // same user  
311 21/06/22 07:31  JANE DOE    
295 19/06/22 17:54  JOHN DOE2 // same user  
289 19/06/22 16:19  JOHN DOE2 // same user

date is a timestamp type.

CodePudding user response:

Your issue is that your date column also includes the the time, so you will only be grouping transactions that occurred at the same time. You also have various grouping issues that will show when you upgrade to MySQL 5.7 or later. This query should give you the results you want:

SELECT DATE_FORMAT(date, '%d/%m/%y') AS ddate,
       name, 
       id_user, 
       SUM(total_amount) AS total_amount
FROM CAJA 
WHERE active != 0 
GROUP BY id_user, name, ddate 
ORDER BY ddate DESC;

Output (for the sample data in your question):

ddate       total_amount    name        id_user
22/06/26    24.40           JOHN DOE1   1
22/06/21    12.50           JANE DOE    2
22/06/19    6.10            JOHN DOE2   3

Demo on db-fiddle

  • Related