是否可以透视表而无需汇总或汇总空值?
例如我有类似的查询
apiController.post(path,params) { response -> // Logic }}
导致
select
PERS_AREA_NAME,
EMP_FIRST_NAME + ' ' + EMP_LAST_NAME as 'CHIEF COUNSEL',
NULL AS 'APPROVER'
from
dbo.IES_HR_EMPLOYEES
where
JOB_NAME like '%Chf Cnsl%'
UNION ALL
select
PERS_AREA_NAME,
NULL,
EMP_FIRST_NAME + ' ' + EMP_LAST_NAME
from
dbo.IES_HR_EMPLOYEES
where
JOB_NAME like '%Dep Sec%'
order by
1
是否可以汇总空值?
PERS_AREA_NAME CHIEF_COUNSEL APPROVER
-----------------------------------------
one Bob Jones Null
one Fred Smith Null
one Null Mary Smith
two John Doe Null
two Null Will Jones
two Null Fred Stevens
答案 0 :(得分:3)
不是执行两个查询的全部UNION,而是使用ROW_NUMBER()作为JOIN条件进行FULL OUTER JOIN。
答案 1 :(得分:2)
对于您而言,我认为最好的方法是忘记多个子查询,而只是使用一种聚合形式:
select pers_area_name,
max(chief_counsel) as chief_counsel,
max(approver) as approver
from (select PERS_AREA_NAME, (EMP_FIRST_NAME + ' ' + EMP_LAST_NAME) as name,
(CASE WHEN JOB_NAME like '%Chf Cnsl%' THEN name END) as chief_counsel,
(CASE WHEN JOB_NAME like '%Dep Sec%' THEN name END) as approver,
ROW_NUMBER() OVER (PARTITION BY (CASE WHEN JOB_NAME like '%Chf Cnsl%' THEN 1 ELSE 2 END)
ORDER BY (SELECT NULL)
) as seqnum
from dbo.IES_HR_EMPLOYEES e cross apply
(values (EMP_FIRST_NAME + ' ' + EMP_LAST_NAME)) v(name)
where JOB_NAME like '%Chf Cnsl%' OR JOB_NAME like '%Dep Sec%'
) e
group by PERS_AREA_NAME, seqnum;
order by 1;
其背后的想法比查询更简单。基本上,它只是在单个子查询中跟踪首席顾问和批准者。关键思想是row_number()
(按职务)。这样,聚合就可以为结果集中的每一行选取值。
这确实假设一个人(雇员表中的行)没有包含“ Chf Cnsl”和“ Dep Sec”的职位。