0

扩展写入 sql 查询以包装行数据的问题

    DEPARTMENT  |   SUB_DEPT    |   EMPLOYEE    |   SALARY
    DEPT1       |   SUB_DEPT1   |   ABC         |   20000
    DEPT1       |   SUB_DEPT1   |   DEF         |   30000
    DEPT1       |   SUB_DEPT2   |   GHI         |   25000
    DEPT1       |   SUB_DEPT2   |   JKL         |   42000
    DEPT2       |   SUB_DEPT3   |   MNO         |   42500
    DEPT2       |   SUB_DEPT3   |   PQR         |   35000
    DEPT3       |   SUB_DEPT4   |   STU         |   36000
    DEPT3       |   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

这意味着1)包装必须适用于两列。2) 换行文本必须用于第一行,即 DEPT1 必须仅出现在第一行,DEPT2 必须出现在第 5 行。

请帮我解决这个问题。

提前致谢。

4

1 回答 1

2

您可以遵循与原始帖子相同的过程。为每个唯一部门创建一个row_number(),然后对每个唯一部门sub_dept 分区执行相同的操作:

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

请参阅带有演示的 SQL Fiddle

结果:

| 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 |
于 2013-01-09T10:34:58.887 回答