这是我的问题:
Select DISTINCT YEAR(THEDELIVERY) as YR,
(Select COUNT(*) from CS462MCMT.vehiclev1 where THEMAKE='Audi') as "No of Audis",
(Select COUNT(*) from CS462MCMT.vehiclev1 where THEMAKE='Volvo') as "No of Volvos",
(Select COUNT(*) from CS462MCMT.vehiclev1 where THEMAKE='Porche') as "No of Porsches",
(Select COUNT(*) from CS462MCMT.vehiclev1 where THEMAKE <> 'Audi' and THEMAKE <> 'Volvo' and THEMAKE <> 'Porche') as "No of Other"
from CS462MCMT.vehiclev1;
第一列显示2008年的两个不同年份值,然后是2007年。我正在尝试根据两个不同的年份值来获取表格中每个品牌汽车的数量。我希望我的输出看起来如下(它目前在2008年和2007年都具有相同的计数值):
Year No of Audis No of Volvos etc.
---- ----------- ------------
2008 1700 3000
2007 300 100
非常感谢任何帮助或建议。
答案 0 :(得分:3)
将GROUP BY
与条件SUM
(SUM
与CASE
)一起使用:
SELECT YEAR(THEDELIVERY) AS "Year",
SUM(CASE THEMAKE WHEN 'Audi' THEN 1 ELSE 0 END) AS "No of Audis",
SUM(CASE THEMAKE WHEN 'Volvo' THEN 1 ELSE 0 END) AS "No of Volvos",
SUM(CASE THEMAKE WHEN 'Porsche' THEN 1 ELSE 0 END) AS "No of Porsches",
SUM(CASE WHEN THEMAKE NOT IN ('Audi','Volvo','Porsche') THEN 1 ELSE 0 END)
AS "No of Other"
FROM CS462MCMT.vehiclev1
GROUP BY YEAR(THEDELIVERY)