SQL在case语句中使用count

时间:2017-04-12 11:07:25

标签: sql count group-by case

我正在尝试对计数小于5的所有活动进行分组(出于数据共享的原因)。

ID代码和ID名称为我提供了高级别的数字,但是一旦我加入“商店代码”,我就会得到一些低级别的数字,这些客户可以去奇数商店一两次。

Select  Count(*) [Activity],
        T.[ID Code],
        T.[ID Name],
        Case when Count(*) < 6 then 'Other Shop' Else T.Shop End [Shop Code]
From    MyTable T
Group By T.[ID Code],
         T.[ID Name],
         Case when Count(*) < 6 then 'Other Shop' Else T.Shop End

但显然我不能在案例陈述中使用计数。我已经尝试了一些类似问题的解决方案,但没有一个有效!

由于

4 个答案:

答案 0 :(得分:1)

问题是GROUP BY

Select  Count(*) as [Activity],
        T.[ID Code],
        T.[ID Name],
        (Case when Count(*) < 6 then 'Other Shop' Else T.Shop
         End) as [Shop Code]
From    MyTable T
Group By T.[ID Code],
         T.[ID Name];

汇总函数(或带有聚合的表达式)不属于GROUP BY。这些计算SELECT中,不用于定义组。

答案 1 :(得分:0)

您可以使用HAVINGUNION ALL语句,如下所示:

Select  Count(*) as [Activity],
    T.[ID Code],
    T.[ID Name],
    'Other Shop' [Shop Code]
 From MyTable T
Group By T.[ID Code],
      T.[ID Name]
having Count(*) < 6
 union all
Select  Count(*) as [Activity],
    T.[ID Code],
    T.[ID Name],
    T.Shop [Shop Code]
 From MyTable T
Group By T.[ID Code],
      T.[ID Name]
having Count(*) >= 6

答案 2 :(得分:0)

select 
count(*) as activity,
code,
name,
Case when Count(*) < 6 then 'Other Shop' Else shopcode End as shopcode
from mytable group by code, name ,shopcode

答案 3 :(得分:0)

以下示例是SQL Server中的测试。

它使用窗口函数进行计数,以更改商店代码 然后将其全部分组,包括修改过的商店代码。

declare @ShopTable table ([ID Code] varchar(30), [ID Name] varchar(30), Shop varchar(30));

insert into @ShopTable ([ID Code], [ID Name], Shop) values 
('S1','Shop 1','AA'),
('S1','Shop 1','BB'),
('S1','Shop 1','BB'),
('S1','Shop 1','CC'),
('S1','Shop 1','CC'),
('S1','Shop 1','CC'),
('S2','Shop 2','XX'),
('S2','Shop 2','YY');

select 
count(*) as [Activity], 
[ID Code], 
[ID Name], 
[Shop Code]
from (
  select
   [ID Code],
   [ID Name],
   case when count(*) over (partition by [ID Code], [ID Name]) < 6 then 'Other Shop' else Shop end as [Shop Code]
  from @ShopTable
) Q
group by [ID Code], [ID Name], [Shop Code];