SQL - 来自多层SELECT语句的数据透视表

时间:2014-12-22 16:08:42

标签: sql-server pivot pivot-table

我有一个SELECT语句,如下所示:

SELECT

d.CODE,
a.ANAPARA - Isnull(b.ANAPARA,0) AS ANAPARA,
d.NAME_,
c.DUEDATE,
a.TAKSIT - Isnull(b.TAKSIT,0) AS TAKSIT,
e.CURCODE

FROM
(SELECT 
PARENTREF,
SUM(TOTAL) AS ANAPARA,
SUM(INTTOTAL) AS FAIZ,
SUM(BSMVTOTAL) AS BSMV,
SUM(KKDFTOTAL) AS KKDF,
SUM(TOTAL+INTTOTAL+BSMVTOTAL+KKDFTOTAL) AS TAKSIT

    FROM LG_011_BNCREPAYTR 
    WHERE TRANSTYPE = 0 
    GROUP BY PARENTREF) a 

LEFT OUTER JOIN (SELECT
PARENTREF,
SUM(TOTAL) AS ANAPARA,
SUM(INTTOTAL) AS FAIZ,
SUM(BSMVTOTAL) AS BSMV,
SUM(KKDFTOTAL) AS KKDF,
SUM(TOTAL+INTTOTAL+BSMVTOTAL+KKDFTOTAL) AS TAKSIT
    FROM LG_011_BNCREPAYTR 
    WHERE TRANSTYPE = 1 
    GROUP BY PARENTREF) b 
ON a.PARENTREF = b.PARENTREF

INNER JOIN (SELECT
 PARENTREF,
 CREDITREF,
 DUEDATE,
 OPRDATE
 FROM LG_011_BNCREPAYTR) c
ON a.PARENTREF=c.PARENTREF

INNER JOIN LG_011_BNCREDITCARD d
ON c.CREDITREF=d.LOGICALREF

INNER JOIN L_CURRENCYLIST e
ON d.TRCURR=e.CURTYPE OR (d.TRCURR=0 AND e.CURTYPE=160)

WHERE e.FIRMNR=11

本规范生成如下表格:

   CODE      ANAPARA             NAME_          DUEDATE      TAKSIT      CURCODE
    001       103.35          CAR LOAN       2015-01-01      150.01          USD
    002       106.89     CONSUMER LOAN       2015-03-10      190.35          EUR
    003       110.44          CAR LOAN       2015-04-20      200.51          YEN
    004       103.22          CAR LOAN       2015-05-04      150.02          EUR

只有3 CURCODE个值(货币):USDEURYEN

我想要一个PIVOT表,其中DUEDATE是x轴,CURCODE是y轴,TAKSIT是聚合的。为了演示,我想要下表:

   CODE      ANAPARA             NAME_          DUEDATE          EUR        USD        YEN
    001       103.35          CAR LOAN       2015-01-01         NULL     150.01       NULL   
    002       106.89     CONSUMER LOAN       2015-03-10       190.35       NULL       NULL
    003       110.44          CAR LOAN       2015-04-20         NULL       NULL     200.51
    004       103.22          CAR LOAN       2015-05-04       150.02       NULL       NULL

感谢很多。

1 个答案:

答案 0 :(得分:0)

无论查询的复杂程度如何,只要被旋转的列与内部选择返回的列匹配,您就可以将其包装然后PIVOT如下所示。我在SUM

上假设TAKSIT聚合
SELECT *
FROM
(
  SELECT * 
   FROM 
   YourReallyComplexQueryHere
) x
PIVOT
(
  SUM(TAKSIT)
  FOR CURCODE IN ([USD], [EUR], [YEN])
) xx;

SqlFiddle here