简体   繁体   English

GROUP BY 用户 ID 和 mysql 中的日期

[英]GROUP BY user id and day in mysql

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:我需要按 id_user 和 DAY 分组,只显示有债务的用户,所以我有这个查询:

$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. date 是时间戳类型。

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.您的问题是您的date列还包括时间,因此您只会对同时发生的交易进行分组。 You also have various grouping issues that will show when you upgrade to MySQL 5.7 or later.当您升级到 MySQL 5.7 或更高版本时,您还会遇到各种分组问题。 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 db-fiddle上的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM