我显示每日基础数据。 Say One Human(HumanID)每天早晚吃2次。所以我输入这样的数据。
表:报告
-----------------------------------------------
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 |
答案 0 :(得分:1)
您可以尝试使用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
答案 1 :(得分:0)
E.g:
select HumanID, date,
Sum(case when schedule = 'morning' then amount end) as morning,
Sum(case when schedule = 'evening' then amount end) as evening
from report
group by HumanID, date
With ROLLUP