gpt4 book ai didi

php - 你会如何整理这个Mysql查询逻辑

转载 作者:行者123 更新时间:2023-11-29 11:20:31 26 4
gpt4 key购买 nike

我正在显示每日数据。说一个人(HumanID)每天早上和晚上吃两次。所以我像这样输入数据。

表格:报告

-----------------------------------------------
ID | HumanID | date | schedule | amount|
-----------------------------------------------
1 | 101 | 2016-01-01 | morning | 10 |
2 | 101 | 2016-01-01 | evening | 8 |
3 | 102 | 2016-01-01 | morning | 11 |
4 | 102 | 2016-01-01 | evening | 9 |
5 | 103 | 2016-01-01 | morning | 8 |
6 | 103 | 2016-01-01 | evening | 7 |

我做Mysql查询:

select HumanID, date, 
max(case when schedule = 'morning' then amount end) as morning,
max(case when schedule = 'evening' then amount end) as evening
from report
group by HumanID, date;

查询后,结果是这样的

---------------------------------------
HumanID | date | morning | evening |
---------------------------------------
101 | 2016-01-01 | 10 | 8 |
102 | 2016-01-01 | 11 | 9 |
103 | 2016-01-01 | 8 | 7 |

我想要的 php 逻辑,结果将如下所示

---------------------------------------
HumanID | date | morning | evening |
---------------------------------------
101 | 2016-01-01 | 10 | 8 |
102 | 2016-01-01 | 11 | 9 |
103 | 2016-01-01 | 8 | 7 |
------------------------------------------
Total: | 29 | 24 |

最佳答案

您可以尝试使用 UNION 添加此结果:

SELECT CAST(t.humanID as char) as humanID,t.date,
MAX(.... )
..... -- Rest of your query
UNION ALL
SELECT 'total:' as humanID , null ,
SUM(case when schedule = 'morning' then amount end) ,
SUM(case when schedule = 'evening' then amount end)
FROM report
ORDER BY humanID

关于php - 你会如何整理这个Mysql查询逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39011668/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com