Sql server 将查询结果换行
延伸问题在哪里 检索像Sql server 将查询结果换行,sql-server,Sql Server,延伸问题在哪里 检索像 DEPARTMENT | SUB_DEPT | EMPLOYEE | SALARY DEPT1 | SUB_DEPT1 | ABC | 20000 | | DEF | 30000 | SUB_DEPT2 | GHI | 25000
DEPARTMENT | SUB_DEPT | EMPLOYEE | SALARY
DEPT1 | SUB_DEPT1 | ABC | 20000
| | DEF | 30000
| SUB_DEPT2 | GHI | 25000
| | JKL | 42000
DEPT2 | SUB_DEPT3 | MNO | 42500
| | PQR | 35000
DEPT3 | SUB_DEPT4 | STU | 36000
| SUB_DEPT5 | VWX | 36040
这意味着
1) 包装必须适用于两列。
2) 换行文字必须用于第一行,即DEPT1必须仅出现在第一行,DEPT2出现在第五行
请帮我解决这个问题
提前感谢。您可以按照与原始帖子相同的流程操作。为每个唯一的部门创建一个
行编号()
,然后对每个唯一的部门和子部门分区执行相同的操作:
select
case when deptrn = 1 then department else '' end department,
case when SubDeptRn = 1 then sub_dept else '' end sub_dept,
employee,
salary
from
(
select department, sub_dept, employee, salary,
row_number() over(partition by department order by department, employee) DeptRn,
row_number() over(partition by department, sub_dept order by department, sub_dept, employee) SubDeptRn
from yourtable
) src
看
结果:
| DEPARTMENT | SUB_DEPT | EMPLOYEE | SALARY |
----------------------------------------------
| DEPT1 | SUB_DEPT1 | ABC | 20000 |
| | | DEF | 30000 |
| | SUB_DEPT2 | GHI | 25000 |
| | | JKL | 42000 |
| DEPT2 | SUB_DEPT3 | MNO | 42500 |
| | | PQR | 35000 |
| DEPT3 | SUB_DEPT4 | STU | 36000 |
| | SUB_DEPT5 | VWX | 36040 |
| DEPARTMENT | SUB_DEPT | EMPLOYEE | SALARY |
----------------------------------------------
| DEPT1 | SUB_DEPT1 | ABC | 20000 |
| | | DEF | 30000 |
| | SUB_DEPT2 | GHI | 25000 |
| | | JKL | 42000 |
| DEPT2 | SUB_DEPT3 | MNO | 42500 |
| | | PQR | 35000 |
| DEPT3 | SUB_DEPT4 | STU | 36000 |
| | SUB_DEPT5 | VWX | 36040 |