这与this discussion有关,但在格式和执行方面有所不同(显然)。我尝试过使用那里的信息而没有合理的结果。
案例:公司有多个部门。我们想知道我们在哪里赚钱。
我们的表格如下 -
Date | Total | Item Description
-----------------------------------
12122012 1000 Butter cookies
12122012 600 Chocolate Coins
12122012 1500 Candy Canes
12142012 1300 Apple Pie
12142012 1300 Pumpkin Pie
12142012 900 Chocolate Cookies
我想保留原样的格式,但是用糖果,饼干和馅饼对产品进行分组。我们的代码如下所示:
SELECT Payments_ReceivedDate AS date, CAST(sum(Payments_Amount) AS UNSIGNED ) as total,
tblTreats.Item_Description as 'Item Description'
FROM tblPayments
INNER JOIN tblTreats ON tblPayments.Items_Ordered = tblTreats.Treats_PK
WHERE Payments_ReceivedDate BETWEEN '20120101' AND '20140101'
GROUP BY Items_Ordered
任何帮助都将不胜感激。
答案 0 :(得分:0)
-- use a subquery
select sum(case when Item_Description in ('Candy Canes') then total end) as Candies_total,
sum(case when Item_Description in ('Butter cookies', 'Butter cookies','Chocolate Cookies') then total end) as Cookies_total,
sum(case when Item_Description in ('Apple Pie','Pumpkin Pie') then total end) as Pies_total
from (SELECT Payments_ReceivedDate AS date, CAST(sum(Payments_Amount) AS UNSIGNED ) as total,
tblTreats.Item_Description as Item_Description
FROM tblPayments
INNER JOIN tblTreats ON tblPayments.Items_Ordered = tblTreats.Treats_PK
WHERE Payments_ReceivedDate BETWEEN '20120101' AND '20140101'
GROUP BY Items_Ordered) AS t