Sql - 计数表查询错误

时间:2015-11-10 15:12:02

标签: sql sql-server

我有一个查询,我想显示车主和他们乘坐汽车,公共汽车或火车的次数。 所以表格看起来应该是这样的;

Owner | Car | Bus | Train
-------------------------
Joe   | 1   | 2   | 4

这是我的查询;

Select owner, vehicle
From MyTable
    INNER JOIN(select  
  count(case when vehicle = 'Car' then 1 else 0 end) AS [Car],
  count(case when vehicle = 'Bus' then 1 else 0 end) AS [Bus],
  count(case when vehicle = 'Train' then 1 else 0 end) AS [Train]
from dbo.MyTable
where
     YEAR([CreatedOn]) = 2015
group by 
    vehicle)

我收到错误的语法错误

3 个答案:

答案 0 :(得分:2)

首先,使用sum()而不是count()。其次,您不需要子查询。第三,您需要按owner分组,而不是vehicle

Select owner,
       sum(case when vehicle = 'Car' then 1 else 0 end) AS [Car],
       sum(case when vehicle = 'Bus' then 1 else 0 end) AS [Bus],
       sum(case when vehicle = 'Train' then 1 else 0 end) AS [Train]
From MyTable
where YEAR([CreatedOn]) = 2015
group by owner;

您可以使用count(),但它会计算非NULL值,因此会产生误导。例如,在您的情况下,条件逻辑被忽略。

编辑:

要完成剩下的工作,请使用相同的想法,只需更改条件:

       sum(case when vehicle not in ('Car', 'Bus', 'Train') then 1 else 0 end) AS Others

答案 1 :(得分:1)

试试这个:

select owner
    ,count(case when vehicle = 'Car' then 1 end) as [Car]
    ,count(case when vehicle = 'Bus' then 1 end) as [Bus]
    ,count(case when vehicle = 'Train' then 1 end) as [Train]
from dbo.MyTable
where year([CreatedOn]) = 2015
group by owner

答案 2 :(得分:1)

你不能使用ELSE 0,因为它会被计算在内。使用ELSE NULL或保留默认值。

Select owner,
     count(case when vehicle = 'Car' then 1 end) AS [Car],
     count(case when vehicle = 'Bus' then 1 end) AS [Bus],
     count(case when vehicle = 'Train' then 1 end) AS [Train],
     count(case when vehicle NOT IN ('Car', 'Bus', 'Train') 
                OR vehicle IS NULL THEN 1 END) AS [Others]
from dbo.MyTable
where YEAR([CreatedOn]) = 2015
group by owner;