使用SQL Server进行条件查询分组

时间:2018-10-27 05:48:24

标签: sql sql-server

这是我的查询,我只是在有条件的情况下尝试分组。

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

但是我遇到了错误

  

')'附近的语法不正确

这是什么原因?

2 个答案:

答案 0 :(得分:1)

您的代码根本不需要CASE,因为CardTypeCustomerType已经在GROUP BY中了:

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

我质疑是否需要GROUP BY,因为您没有聚合功能。您甚至可以将表达式添加到SELECT

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

请注意,如果CardTypeCustomerType具有不同的类型,则可能会导致类型转换错误。

答案 1 :(得分:0)

您刚刚错过了end

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