sql - SQL Server pivot a table without aggregating
问题描述
Is it possible to pivot a table without aggregating or roll up the nulls?
For example I have a query something like
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
That results in
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
Is it possible to rollup the nulls?
PERS_AREA_NAME CHIEF_COUNSEL APPROVER
------------------------------------------------
one Bob Jones Mary Smith
one Fred Smith Null
two John Doe Will Jones
two Null Fred Stevens
解决方案
Instead of doing a UNION ALL of the two queries, do a FULL OUTER JOIN using ROW_NUMBER() as the JOIN condition.
推荐阅读
- python - 在python中有条件地处理JSON
- c++ - 递归类定义产生c ++中的无效指针
- php - php artisan migrate 命令错误,找不到驱动程序
- python - 使用 pandas 或 numpy 进行高级切片,用于 2 对和 3 对,5 组
- python - 如何在单元格之间打印一行带有单个空格的数据框?
- java - 我如何计算每个省有多少男性和女性,并且这些省按国家字母顺序排列?
- javascript - 在 javascript 中执行 http 请求响应
- php - 在 GCP App Engine 上安装 PHP 扩展
- r - R - 删除除最近日期以外的所有行?
- lua - 桌面模拟器中的 LUA 脚本