1

I'm trying to group all activity where the count is less than 5 (for data sharing reasons).

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.

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. I've tried some of the solutions to similar questions but none of them work!

Thanks

1
  • case expression, not statement. Commented Apr 12, 2017 at 11:12

4 Answers 4

1

The problem is the 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. These are calculated in the SELECT, not used to define groups.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the HAVING and UNION ALL statement, like this:

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

Comments

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

Comments

0

The example below is a test in 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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.