这是我的数据
COUNTYID POLLUTANT TYPE EMISSION
1 A 1
1 A 2
1 B 1
1 B 2
2 A 1
2 A 2
2 B 1
2 B 2
3 A 1
3 A 2
3 B 1
3 B 2
如果我这样做
SELECT sum(EMISSION) from table where POLLUTANT = 'A' group by COUNTYID;
我会受到Polutant&A 39的污染。如何编写查询以获取以下数据:
第1列,总和为A,第2列为B的总和,第3列为A和B的总和?
谢谢
答案 0 :(得分:1)
您可以使用大小写来过滤您需要的值
select COUNTYID, sum(case when POLLUTANT='A'then EMISSION else 0 END) tot_a
, sum(case when POLLUTANT='B'then EMISSION else 0 END) tot_b
, sum(EMISSION) tot_a_b
from my_table
group by COUNTYID
答案 1 :(得分:1)
您可以使用条件聚合。这会将过滤条件从where
子句移动到sum()
s:
select countyid,
sum(case when emission = 'A' then emission else 0 end) as A,
sum(case when emission = 'B' then emission else 0 end) as B,
sum(emission) as total
from t
group by countyid;
答案 2 :(得分:0)
我想提出一些想法。我们可以使用数据透视表来回答您的问题
SELECT * from dbo.[Table_1]
PIVOT
(Sum([type_emmssion]) for [polutant] in ([A], [B]) ) as PivotTable
group by [CountryId] ;
答案 3 :(得分:0)
你必须使用case statemet:
SELECT
SUM( CASE WHEN POLLUTANT = 'A' THEN EMISSION ELSE 0 END) AS A_EMISSION
SUM( CASE WHEN POLLUTANT = 'B' THEN EMISSION ELSE 0 END) AS B_EMISSION
SUM(EMISSION) AS total_emission
FROM table
GROUP BY COUNTYID;