这是静态数据透视SQL查询。
WITH
T
AS
(
SELECT
DEPTNO
FROM
EMP
)
SELECT
*
FROM
T
PIVOT
(
COUNT(*)
FOR
(DEPTNO)
IN
(10,20,30,40)
但是我想对矩阵报表进行动态SQL查询。标题名称将是部门名称而不是部门ID。那我现在该怎么办?
答案 0 :(得分:0)
我认为这应该对您有用。您需要给别名一个别名,以使其成为首选:
SELECT
'empname' as empname ,[0] as yourdepartname1, [1] as yourdepartname2, [2] as yourdepartname2, [3]yourdepartname4, [4] as yourdepartname5
FROM
(
SELECT
empname,DEPTNO
FROM
EMP e
inner join department d on d.DEPTNO on e.deptno
group by empname) p
PIVOT
(
COUNT(*)
FOR
(empname)
IN
([0], [1], [2], [3], [4] ))
AS PivotTable