2010-06-03 86 views
0

表名是Looupvalue使用sql server 2008將行轉換爲列?

id Ptypefield Value 
1 1 D 
2 1 E 
3 1 F 
4 1 G 
5 1 H 
6 2 FL 
7 2 IF 
8 2 VVS1 
9 2 VVS2 
10 2 VS1 
11 2 VS2 
12 3 0.50 
13 3 1.00 
14 3 1.50 
15 3 2.00 
16 4 Marquise 
17 4 Round 
18 4 Pear 
19 4 Radiant 
20 4 Princess 

Lookupvalue表值轉換roow列取決於ptypefield

id 1 id 2  id 3  id 4 
1 D 6 fl  12 0.50 16 Marquise 
2 E 7 If  13 1  17 Round.... 
3 F 8 vvs2 14 1.5 
4 G 9 vvs2  15 2 
5 H 10 vs1 
     11 vs2 

感謝

+1

這可能讓你開始http://stackoverflow.com/questions/1534959/sql-server-2005-pivoting-data-without-a-sum-count-and-dynamic-list-of-values – 2010-06-03 12:00:39

+0

在你的樣本輸出,第1列和第2列中的數據如何與第3列和第4列或第5列和第6列相關?也就是說,爲什麼'D'出現在與「FL」相同的行而不是「IF」?那是隨機的嗎? – Thomas 2010-06-03 15:07:13

回答

0

在你的樣品輸出,目前尚不清楚爲什麼第1列和第2列的值將與第3列和第4列相關。但是,這裏有一個可能的解決方案:

;With RowNumbers As 
    (
    Select Id, PTypeField, Value 
     , Row_Number() Over(Partition By PTypeField Order By Id) As Rownum 
    From #Test 
    ) 
Select RowNum 
    , Min(Case When PTypeField = 1 Then Id End) As Id 
    , Min(Case When PTypeField = 1 Then Value End) As [1] 
    , Min(Case When PTypeField = 2 Then Id End) As Id 
    , Min(Case When PTypeField = 2 Then Value End) As [2] 
    , Min(Case When PTypeField = 3 Then Id End) As Id 
    , Min(Case When PTypeField = 3 Then Value End) As [3] 
    , Min(Case When PTypeField = 4 Then Id End) As Id 
    , Min(Case When PTypeField = 4 Then Value End) As [4] 
From RowNumbers 
Group By RowNum 

如果您想動態生成列,那麼在SQL中執行該操作的唯一方法是使用一些非常動態的SQL。 T-SQL不是爲這種輸出而設計的,而應該使用報告工具或在中間層組件或類中進行交叉表示。

這個數據模式看起來像一個EAV,這將解釋爲什麼檢索你想要的數據是如此困難。

+0

謝謝...我想知道如何創建這個查詢動態例如 ptypefield是一些時間4或某些時間7等,所以我想創建查詢.... plz給我想法.... – kanth 2010-06-03 21:59:18

+0

@jaykanth - 動態交叉表(這正是你正在尋找的)不在SQL Server的主流功能之中。雖然在T-SQL中可以做到這一點非常麻煩,並且不會像在用C#或報告工具編寫的中間層組件中那樣執行。 – Thomas 2010-06-03 22:39:59