简体   繁体   English

SQL使用case语句

[英]SQL using count in case statement

I'm trying to group all activity where the count is less than 5 (for data sharing reasons). 我正在尝试将计数少于5的所有活动分组(出于数据共享的原因)。

The ID Code and ID Name give me high level numbers, but as soon as I include "shop code" I get some low level numbers for customers that go to odd shops once or twice. 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

But obviously I can't use a count in a case statement. 但是显然我不能在case语句中使用计数。 I've tried some of the solutions to similar questions but none of them work! 我已经尝试了一些解决类似问题的方法,但是没有一个起作用!

Thanks 谢谢

The problem is the GROUP BY : 问题是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];

Aggregate functions (or expressions with aggregates) don't belong in the GROUP BY . 聚集函数(或具有聚集的表达式)不属于GROUP BY These are calculated in the SELECT , not used to define groups. 这些是在SELECT计算的,不用于定义组。

You can use the HAVING and UNION ALL statement, like this: 您可以使用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
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

The example below is a test in SQL Server. 下面的示例是在SQL Server中的测试。

It uses a window function for count, to change the Shop code. 它使用窗口功能进行计数,以更改商店代码。
And then groups it all, including that modified shopcode. 然后将所有内容分组,包括修改后的商店代码。

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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM