2017-01-09 120 views
-1

我有一个表,ID并不是唯一的一行。每个ID最多可以有三行。每个ID的SQL数据透视表

 ID  | Name   |  Quantity 
---------------------------------------------- 
    1   | apple  |  1 
    1   | orange  |  NULL 
    1   | mango  |  3 
    2   | banana  |  5 
    2   | strawberries |  2 
    3   | kiwi   |  NULL 
    3   | lime   |  3 
    3   | grape  |  7 

我想要一个查询,得到这个结果表:

|  ID  | Fruit 1  | Fruit 1 Amount | Fruit 2  | Fruit 2 Amount | Fruit 3  | Fruit 3 Amount  
------------------------------------------------------------------------------------------------------------------------------------ 
|  1  | apple  |   1   |  orange  | NULL    | mango  |  3 
|  2  | banana  |   5   | strawberries | 2     | NULL  |  NULL 
|  3  | kiwi  |  NULL   |  lime  | 3     | grape  |  7 

我想每个ID

+0

的[高效行转换为列在SQL Server](http://stackoverflow.com/questions/15745042/efficiently-convert-rows-to-columns-in-sql-server) –

+0

可能的复制@ TabAlleman在提到的问题中的结果表不是按ID完成的,我想为每个ID编号的行 – Wafae

+0

您可以参考此问题http://stackoverflow.com/questions/15931607/convert-rows-to-columns-using- pivot-in-sql-server –

回答

2

子查询S使用分配行这是在有条件聚集排号外部查询。对于这样简单的事情,我不会打扰枢轴功能。

1> select s.id, 
2> max(case when s.rn = 1 then s.name end) as f1name, 
3> max(case when s.rn = 1 then s.quantity end) as f1qty, 
4> max(case when s.rn = 2 then s.name end) as f2name, 
5> max(case when s.rn = 2 then s.quantity end) as f2qty, 
6> max(case when s.rn = 3 then s.name end) as f3name, 
7> max(case when s.rn = 4 then s.quantity end) as f3qty 
8> from 
9> (
10> select * , 
11> row_number() over(partition by id order by id,name) rn 
12> from t 
13>) s 
14> group by s.id 
15> go 
id   f1name   f1qty  f2name   f2qty  f3name   f3qty 
----------- --------------- ----------- --------------- ----------- --------------- ----------- 
      1 apple      1 mango      3 orange     NULL 
      2 banana     5 strawberries    2 NULL     NULL 
      3 grape      7 kiwi     NULL lime     NULL 

(3 rows affected) 
+0

完美!非常感谢你的帮助 :) – Wafae