Ironsun
Ironsun

Reputation: 881

Group by with condition query using SQL Server

This is my query, I am just trying group by with condition.

select 
    CardType, TypeTitle, EducationType, typetitle, customertype  
from 
    #temprec 
group by 
    (case when CardType = 2 then CardType else CustomerType),
    CardType, TypeTitle, EducationType, typetitle, customertype 

But I am getting an error

Incorrect syntax near ')'

What would be the cause for this?

Upvotes: 0

Views: 53

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269503

Your code does not require the CASE at all because both CardType and CustomerType are already in the GROUP BY:

select CardType, TypeTitle, EducationType, typetitle, customertype  
from #temprec t
group by CardType, TypeTitle, EducationType, typetitle, customertype ;

I question the need for the GROUP BY, because you have no aggregation functions. You can even add the expression to the SELECT:

select distinct (case when CardType = 2 then CardType else CustomerType end),
       CardType, TypeTitle, EducationType, typetitle, customertype  
from #temprec t;

Note that this could get a type conversion error if CardType and CustomerType have different types.

Upvotes: 1

Zaynul Abadin Tuhin
Zaynul Abadin Tuhin

Reputation: 32003

you just missed end after else

select 
        CardType, TypeTitle, EducationType, typetitle, customertype  
    from 
        #temprec 
    group by 
        (case when CardType = 2 then CardType else CustomerType end),
        CardType, TypeTitle, EducationType, typetitle, customertype 

Upvotes: 0

Related Questions