2016-08-18 7 views
0

私は毎日の基本データを表示しています。 1人の人間(HumanID)が毎朝2回食べると言う。だから私はこのようなデータを入力します。どのようにこの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; 

照会した後、結果は私が、結果は意志PHPのロジックで何をしたいです。この

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

のように思いついた:レポート

----------------------------------------------- 
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のクエリを行いますこのように見える

--------------------------------------- 
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 
関連する問題