开发者

CASE inside GROUP BY

How can I selectively choose the columns for group by? Can I use CASE inside it. It compiles alright but doesnt seem to work at run time.

example:

GROUP BY o.organization_name ol.org_level_name开发者_开发百科, work_date,
 CASE WHEN @org_level_type = 'Department' THEN jd.job_code ELSE jd.job_department_id END

Thanks.


Edited Answer

This is probably not a good idea. Just divide it into 2 separate queries to avoid unnecessary sort operations from a one size fits all query.

You could put the bulk of the query that is doing the joins on tables o,jd,ol (without a GROUP BY) into a View to avoid having to repeat this.

Original Answer

(Assuming the 2 columns are of compatible datatypes)

select o.organization_name,
       ol.org_level_name,
       work_date,
       code_or_dept
FROM   ...
       CROSS APPLY (SELECT CASE
                             WHEN @org_level_type = 'Department' THEN
                             jd.job_code
                             ELSE jd.job_department_id
                           END AS code_or_dept) c
GROUP  BY o.organization_name,
          ol.org_level_name,
          work_date,
          code_or_dept  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜