【问题标题】:Header and sub header to be inserted between the records without using SQL cursors在不使用 SQL 游标的情况下插入记录之间的标题和子标题
【发布时间】:2016-09-08 12:35:05
【问题描述】:

下面是员工表

| emp_id |员工名 | emp_type | emp_status |参加过的课程 |


1 AAA ON ROLL'A'2

2 BBB承包商'4

  3               CCC              滚动             '我'                         1

  4               CDS            承包商         '我'                         7

  5               艾达                                                                                                                2

  6               BfB            承包商         'A'                         2


有了这个我需要下面的输出而不使用光标

第 1 列    第 2 列

滚动         5
-状态“A”   4
AAA          2
AdA           2
-状态“我”     1
CCC         1
承包商   13
-状态“A”   6
BBB         4
BfB           2
-状态“我”     7
CDS         7

我需要同一列中的所有标题、子标题和 emp 名称。

【问题讨论】:

  • 这不是在 SQL 中可以轻松完成的工作,最好在应用程序代码中完成。

标签: sql sql-server pivot cursors


【解决方案1】:
select emp_type, emp_status, course_attended, 1 as order1, 1 as order2
from employee e
union all
select emp_type, emp_status, sum(course_attended), 1 as order1, 0 as order2
from employee e
group by emp_type, emp_status
union all
select emp_type, '' as emp_status, sum(course_attended), 0 as order1, 0 as order2
from employee e
group by emp_type

order by emp_type, emp_status, order1, order2

【讨论】:

  • 我正在寻找我展示的树状结构。我需要同一列中的所有标题、子标题和 emp 名称。
【解决方案2】:

您所询问的输出格式在 SQL 中有点困难。但是您可以尝试以下方法,然后根据您在 PLSQL 中的要求重新构建结果。

SELECT EMP_TYPE ||'--'||EMP_STATUS||'--'||EMP_NAME,SUM(COURSE_ATTENDED) FROM
(SELECT 1 EMP_ID ,'AAA' EMP_NAME,'On Roll' EMP_TYPE, 'A' EMP_STATUS, 2 COURSE_ATTENDED FROM dual
UNION ALL
SELECT 2 ,'BBB', 'Contractor' , 'A' , 4 FROM dual
UNION ALL
SELECT 3 , 'CCC' , 'On Roll', 'I' , 1 FROM dual
UNION ALL
SELECT 4 , 'CDS' , 'Contractor' , 'I' , 7 FROM dual
UNION ALL
SELECT 5 , 'Ada' , 'On Roll' , 'A' , 2 FROM dual
UNION ALL
SELECT 6 , 'BfB' , 'Contractor' , 'A' , 2 FROM dual)
GROUP BY GROUPING SETS ((EMP_TYPE),(EMP_TYPE,EMP_STATUS),(EMP_TYPE,EMP_STATUS,EMP_NAME));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 2015-04-05
    • 2011-12-06
    • 1970-01-01
    相关资源
    最近更新 更多