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
精彩评论