我有一张这样的桌子:
Date | Name | Pick | Amount
-----------+-------+-------+-------
2018-01-01 | Alice | Apple | 2
2018-01-01 | Alice | Grape | 3
2018-01-01 | Bob | Apple | 4
2018-01-02 | Alice | Apple | 5
2018-01-02 | Bob | Grape | 6
产生如下所示结果的SQL语句是什么?
Name | Apple | Grape | Total
------+-------+-------+------
Alice | 7 | 3 | 10
Bob | 4 | 6 | 10
答案 0 :(得分:4)
使用CASE
条件,这是可能的。
尝试一下:
select name
,sum(case when pick = 'Apple' then amount end)Apple
,sum(case when pick = 'Grape' then amount end)Grape
,sum(case when pick = 'Apple' then amount end)
+sum(case when pick = 'Grape' then amount end)Total
from your_table
group by name
答案 1 :(得分:2)
您需要条件聚合:
select name,
sum(case when pick = 'Apple' then amount else 0 end) Apple,
sum(case when pick = 'Grape' then amount else 0 end) Grape,
sum(case when pick in ('Apple', 'Grape') then amount else 0 end) Total
from table t
group by name;
答案 2 :(得分:2)
这也是一种使用汇总函数和or
select name,
sum(case when pick = 'Apple' then amount else 0 end) Apple,
sum(case when pick = 'Grape' then amount else 0 end) Grape,
sum(case when pick in('Apple','Grape') then amount else 0 end) Total
from tableA
group by name
答案 3 :(得分:1)
SELECT Name,
sum(if(Pick='Apple', Amount, 0)) as Apple,
sum(if(Pick='Grape', amount, 0)) as Grape
FROM table_name
GROUP BY Name;
答案 4 :(得分:1)
您可以使用嵌套查询。一种用于计算葡萄和苹果,另一种用于计算总量。优点是您可以在单个位置上计算每一列的逻辑,并且总计的计算更加直观
SELECT
Name,
Apple,
Grape,
Apple + Grape as Total
FROM (
SELECT
`name` as Name,
SUM(IF(pick = 'Apple', amount, 0)) as Apple,
SUM(IF(pick = 'Grape', amount, 0)) as Grape
FROM test
GROUP BY name
) AS t1