Sql server common packet aggregation very broad application, but sometimes we need to use a similar excel show the effect of perspective;
So how do you achieve this perspective effect?
In the following example:
To Oracle database scott classic example:
We require each department to show the next (deptno), functional (job) of all comprehensive salary is how much, under normal circumstances we will use the following query
1 select deptno,job,SUM(sal) as sum_sal 2 from emp 3 group by deptno,job
Results are as follows:
But if we ask deptno vertical arrangement, Job horizontal arrangement should be?
Conventional worded as follows:
1 --常规透视 2 select deptno, 3 sum(case when job='ANALYST' then sal else 0 end) as ANALYST, 4 sum(case when job='CLERK' then sal else 0 end) as CLERK, 5 sum(case when job='MANAGER' then sal else 0 end) as MANAGER, 6 sum(case when job='PRESIDENT' then sal else 0 end) as PRESIDENT, 7 sum(case when job='SALESMAN' then sal else 0 end) as SALESMAN 8 from emp 9 group by deptno
The results obtained were as follows:
Used to form the operation of such arrangement might feel a little more intuitive;
当然这是常规的写法,Sql Server 自带的Pivot方法也可以实现:不过对版本的要求至少是2008
如下:
1 --pivot透视 2 select deptno,ANALYST,CLERK,MANAGER,PRESIDENT,SALESMAN 3 from 4 (select deptno,job,sal from emp)as a 5 pivot (sum(sal) 6 for job 7 in (ANALYST,CLERK,MANAGER,PRESIDENT,SALESMAN)) as b
效果同上
但是需要注意一点,如果这个查询的行和列相反(即:deptno横向,job纵向),
因为deptno值全是数值,那么在书写的时候要注意一下,加上"[]",
如下
1 select job,[10],[20],[30] 2 from 3 (select job,deptno,sal from emp) a 4 pivot (sum(sal) 5 for deptno 6 in ([10],[20],[30]) )b
效果如下:
这个是透视,逆透视--未完待续…………