要在不使用SQL游标的情况下插入记录之间的标头和子标头

时间:2016-09-08 12:35:06

标签: sql sql-server pivot cursors

以下是员工表

| emp_id | emp_name | emp_type | emp_status |课程参加|

<小时/> 1 AAA开卷'A'2

2 BBB承包商'A'4

3 CCC On Roll'I '1

4 CDS承包商'我'7

5 Ada On Roll'A'2

6 BfB承包商'A'2

<小时/> 有了这个我需要在不使用光标的情况下输出

Column1 Column2

On Roll 5
-Status'A' 4
AAA 2
ADA 2
-Status'I' 1
CCC 1个
承包商 13
-Status'A' 6
BBB 4
BFB 2
-Status'I' 7
CDS 7个

我需要同一列中的所有标题,子标题和\ temp名称。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您提出的任何输出格式在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));