2017-04-12 119 views
0

我試圖將計數小於5的所有活動(針對數據共享原因)進行分組。SQL在case語句中使用count

身份證號碼和身份證號碼給了我很高的號碼,但只要我包含「商店代碼」,我就會爲一些或兩次前往奇數店鋪的客戶收到一些低級號碼。

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 

但顯然我不能在case語句中使用count。我已經嘗試了類似問題的一些解決方案,但他們都沒有工作!

由於

+0

case expression,not statement。 – jarlh

回答

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,不用於定義組。

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 
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 
0

下面的例子是在SQL Server的測試。

它使用窗口函數count來更改商店代碼。
然後對其進行分組,包括修改後的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];