2012-04-17 82 views

回答

1

事情是這樣的:

測試數據

CREATE TABLE #tbl(date_a DATE,date_e DATE, vals FLOAT) 

INSERT INTO #tbl 
VALUES 
    ('2/29/2012','1/1/2013',28.47), 
    ('2/29/2012','2/1/2013',27.42), 
    ('2/29/2012','3/1/2013',24.36), 
    ('3/1/2012','1/1/2013',28.5), 
    ('3/1/2012','2/1/2013',27.35), 
    ('3/1/2012','3/1/2013',24.39), 
    ('3/6/2012','1/1/2013',27.75), 
    ('3/6/2012','2/1/2013',26.63), 
    ('3/6/2012','3/1/2013',23.66) 

查詢

SELECT 
    * 
FROM 
( 
    SELECT 
     tbl.date_a, 
     tbl.date_e, 
     vals 
    FROM 
     #tbl AS tbl 
) AS SourceTable 
PIVOT 
(
    SUM(vals) 
    FOR date_e IN ([1/1/2013],[2/1/2013],[3/1/2013]) 
) AS pvt 

DROP TABLE #tbl 

編輯

如果你不知道有多少列,那麼你需要做一個動態的pivot。就像這樣:

獨特的列

DECLARE @cols VARCHAR(MAX) 
;WITH CTE 
AS 
(
    SELECT 
     ROW_NUMBER() OVER(PARTITION BY date_e ORDER BY date_e) AS RowNbr, 
     tbl.* 
    FROM 
     #tbl AS tbl 
) 
SELECT @cols=STUFF 
(
    (
     SELECT 
      ',' +QUOTENAME(date_e) 
     FROM 
      CTE 
     WHERE 
      CTE.RowNbr=1 
     FOR XML PATH('') 
    ) 
,1,1,'') 

動態樞

DECLARE @query NVARCHAR(4000)= 
N'SELECT 
    * 
FROM 
( 
    SELECT 
     tbl.date_a, 
     tbl.date_e, 
     vals 
    FROM 
     #tbl AS tbl 
) AS SourceTable 
PIVOT 
(
    SUM(vals) 
    FOR date_e IN ('[email protected]+') 
) AS pvt' 
EXECUTE(@query) 
+0

負載的感謝,它的工作沒有缺陷。一旦時鐘達到兩分鐘屏障就會接受它:) – 2012-04-17 10:50:58

+0

沒問題。很高興幫助:P ..我給你添加了一個獎勵例子:P ..請看看。 – Arion 2012-04-17 10:54:29

+0

這就是真棒!對不起請求更多.. :)謝謝很多陛下.. – 2012-04-17 11:14:43