2010-06-03 30 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

相关问题