2012-02-02 55 views
4

SQL返回從表中的結果如下:CowTracking使行值成列的值 - SQL PIVOT

ID cow_id barn_id 
    -- ------ ------- 
    19 5  3 
    20 5  2 
    21 5  9 
    22 5  1 

我試圖得到一個PIVOT以下結果在SQL

 cow_id barn1 barn2 barn3 barn4 
    ------ ----- ----- ----- ----- 
     5  3  2  9  1 

這是我迄今爲止的代碼。

SELECT * 
    FROM 
    (
     SELECT TOP 4 * 
     FROM CowTracking 
      WHERE cow_id = 5 
    ) AS DataTable 
    PIVOT 
    (
     MIN(barn_id) **IDK what function to use and which column to use it on** 
     FOR ID ??<---**NOT SURE** 
     IN 
     (
     [barn1], [barn2], [barn3], [barn4] 
     ) 
    ) AS PivotTable 


    ERRORS: Error converting data type nvarchar to int 
      The incorrect value "barn1" is supplied in the PIVOT operator 

注意:barn_id是一個varchar。它不可能改變數據類型。

我不想加/乘/聚合或其他。我只是試圖將該行移動到列

我該如何去做這件事? 這是正確的思維過程嗎?

我甚至需要使用PIVOT嗎?

回答

5

由於您的表格中沒有barn1..4,因此您不得不用ID來代替它們相應的barn。使用PIVOT

一種解決方案可能是這樣的

SELECT cow_id 
     , [19] as [barn1] 
     , [20] as [barn2] 
     , [21] as [barn3] 
     , [22] as [barn4] 
FROM (  
      SELECT * 
      FROM DataTable 
      PIVOT ( MIN(barn_id) 
         FOR ID IN ([19], [20], [21], [22]) 
        ) AS PivotTable 
     ) q     

使用CASEGROUP BY另一種解決方案可能是

SELECT cow_id 
     , [barn1] = SUM(CASE WHEN ID = 19 THEN barn_id END) 
     , [barn2] = SUM(CASE WHEN ID = 20 THEN barn_id END) 
     , [barn3] = SUM(CASE WHEN ID = 21 THEN barn_id END) 
     , [barn4] = SUM(CASE WHEN ID = 22 THEN barn_id END) 
FROM DataTable 
GROUP BY 
     cow_id 

,但在本質上,這一切都歸結爲硬編碼的IDbarn


編輯

如果你總是返回記錄固定數量,並使用SQL Server,則可能使這一點更強大的通過

  • 添加ROW_NUMBER每個結果
  • 透視此前期已知號碼

SQL語句

SELECT cow_id 
     , [barn1] = SUM(CASE WHEN rn = 1 THEN barn_id END) 
     , [barn2] = SUM(CASE WHEN rn = 2 THEN barn_id END) 
     , [barn3] = SUM(CASE WHEN rn = 3 THEN barn_id END) 
     , [barn4] = SUM(CASE WHEN rn = 4 THEN barn_id END) 
FROM (
      SELECT cow_id 
        , rn = ROW_NUMBER() OVER (ORDER BY ID) 
        , barn_id 
      FROM DataTable  
     ) q 
GROUP BY 
     cow_id 

測試腳本

;WITH DataTable (ID, cow_id, barn_id) AS (
    SELECT * FROM (VALUES 
     (19, 5, 3) 
     , (20, 5, 2) 
     , (21, 5, 9) 
     , (22, 5, 1) 
    ) AS q (a, b, c)   
) 
SELECT cow_id 
     , [barn1] = SUM(CASE WHEN rn = 1 THEN barn_id END) 
     , [barn2] = SUM(CASE WHEN rn = 2 THEN barn_id END) 
     , [barn3] = SUM(CASE WHEN rn = 3 THEN barn_id END) 
     , [barn4] = SUM(CASE WHEN rn = 4 THEN barn_id END) 
FROM (
      SELECT cow_id 
        , rn = ROW_NUMBER() OVER (ORDER BY ID) 
        , barn_id 
      FROM DataTable  
     ) q 
GROUP BY 
     cow_id 
+1

你的第一個建議是當場上。起初我很擔心,因爲ID會一直改變。但後來我宣佈了一個新的專欄,並設置了它,以便它始終是1 - 4。然後我能夠完成它。感謝隊友,非常感謝。帶我一點點,讓我的頭繞着這個概念 – sQuijeW 2012-02-02 20:34:16

+0

@sQuijeW - 不客氣。如果這回答你的問題,你可以將它標記爲*([接受答案如何工作?](http://meta.stackexchange.com/questions/5234))* – 2012-02-02 20:49:31