0

我有一个带有两个 col1 和 col2 的表 tblInput。
我需要通过查询获得以下输出。

在此处输入图像描述

到目前为止,我已经这样做了:

select col1 + col2 from tblInput order by col1,col2  

但这给出了单列的输出。我想要它在一个矩阵中。
怎么做?

4

2 回答 2

2

您需要PIVOT在查询中使用。请参考示例:

http://www.mssqltips.com/sqlservertip/1019/crosstab-queries-using-pivot-in-sql-server/

于 2012-12-28T06:57:29.887 回答
1
SELECT * FROM (
   SELECT  job
      , sum(decode(deptno,10,sal)) DEPT10
      , sum(decode(deptno,20,sal)) DEPT20
      , sum(decode(deptno,30,sal)) DEPT30
      , sum(decode(deptno,40,sal)) DEPT40
      , sum(sal)                   TOTAL
     FROM scott.emp
   GROUP BY job)
 ORDER BY 1
 /

 JOB           DEPT10     DEPT20     DEPT30     DEPT40      TOTAL
--------- ---------- ---------- ---------- ---------- ----------
ANALYST                    6000                             6000
CLERK           1300       1900        950                  4150
MANAGER         2450       2975       2850                  8275
PRESIDENT       5000                                        5000
SALESMAN                              5600                  5600
于 2012-12-28T15:09:49.510 回答