如何在group by中使用case语句

时间:2021-03-29 22:30:57

I have following case statements in my SELECT clause, also I have a group by clause... So, Is it okay to specify UF.CONT_PID & UF.M_STATUS_CD in my GROUP BY Clause ? I need to specify the entire CASE statement in GROUP BY ?

我的SELECT子句中有以下case语句,我也有一个group by子句...那么,在GROUP BY子句中指定UF.CONT_PID和UF.M_STATUS_CD是否可以?我需要在GROUP BY中指定整个CASE语句吗?

 CASE WHEN UF.CONT_PID IN    
 ('04007005', '01019045','01019046') OR 
 (UF.M_STATUS_CD IN ('01', '02') 
 THEN    
 1    
 ELSE    
0    
 END

2 个解决方案

#1


2  

Rather than repeat the expression, you could do:

您可以这样做,而不是重复表达:

SELECT col /*, other cols */ FROM
(
  SELECT col = CASE WHEN /*...long-winded expression...*/ 
    THEN 1 ELSE 0 END /*, other cols */
  FROM dbo.table
) AS x
GROUP BY col;

#2


0  

I believe you can group by in two ways:

我相信你可以通过两种方式分组:

GROUP BY UF.CONT_PID, UF.M_STATUS_CD

OR

GROUP BY CASE WHEN UF.CONT_PID IN ('04007005', '01019045','01019046') OR (UF.M_STATUS_CD IN ('01', '02') THEN 1 ELSE 0 END

But keep in mind that these are very different groupings.

但请记住,这些是非常不同的分组。

#1


2  

Rather than repeat the expression, you could do:

您可以这样做,而不是重复表达:

SELECT col /*, other cols */ FROM
(
  SELECT col = CASE WHEN /*...long-winded expression...*/ 
    THEN 1 ELSE 0 END /*, other cols */
  FROM dbo.table
) AS x
GROUP BY col;

#2


0  

I believe you can group by in two ways:

我相信你可以通过两种方式分组:

GROUP BY UF.CONT_PID, UF.M_STATUS_CD

OR

GROUP BY CASE WHEN UF.CONT_PID IN ('04007005', '01019045','01019046') OR (UF.M_STATUS_CD IN ('01', '02') THEN 1 ELSE 0 END

But keep in mind that these are very different groupings.

但请记住,这些是非常不同的分组。