MySQL 组合特定字段

标签 mysql

这与 this discussion 相关,但格式和执行不同(显然)。我尝试使用那里的信息,但没有得出合乎逻辑的结果。

案例:公司有多个部门。我们想知道我们在哪里赚钱。

我们的 table 看起来像这样 -

  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

我想保留原样的格式,但按糖果、 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

如有任何帮助,我们将不胜感激。

最佳答案

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

关于MySQL 组合特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25209814/

相关文章:

mysql_query() - 协议(protocol)

mysql - 如何在 MySQL 中重命名 View ?

mysql - 只能使用 --skip-grant-tables 参数访问 mySQL(检查所有其他线程)

mysql - 如何将表名连接到行值以重命名列

php - 计算可能性 PHP、MySqli

php - jQuery .animate 不起作用

php - 在 PHP/MYSQL 中查找最近的邮政编码位置

php - PHP Edit无法正常工作

mysql - 在mysql列的底部显示总和

php - 匹配日期时间不显示结果