0

这是我的查询:

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

任何帮助或建议将不胜感激。

4

1 回答 1

3

GROUP BY与条件SUMSUMwith )一起使用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)
于 2013-03-14T00:17:16.203 回答