2016-08-18 24 views
0

我正在顯示每日基礎數據。說一個人(HumanID)每天早上,晚上吃兩次。所以我輸入這樣的數據。你將如何整理這個Mysql查詢邏輯

表:報告

----------------------------------------------- 
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 | 
+1

你嘗試使用'SUM()在查詢'? – Epodax

+0

到目前爲止您嘗試過哪些PHP? – jedifans

+0

總和而不是最大。和ROLLUP。但實際上我會在PHP中完成這個格式化的部分 – Strawberry

回答

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 
0

例如爲:

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