如何以此格式选择表中的值

时间:2016-07-18 03:44:33

标签: sql sql-server sql-server-2008

我有一张表table1

Item_Name      |   Type     |   Qty   | Amount

   A                Like         2       10
   B                Love         1       20
   C                Ours         1       10
   A                Love         1       10
   A                Like         1       10
   B                Ours         1       10

我需要一个o / p,如下所示

Item_Name            Like | Love | Ours      Like | Love | Ours  
                            Amount                 Qty

  A                   20     10     0          3      1      0
  B                   0      20     10         0      1      1
  C                   0      0      10         0      0      1

我如何实现所需的o / p。我无法实现同样的目标。请帮忙

1 个答案:

答案 0 :(得分:3)

一种方法是使用分组和条件聚合来获得所需的输出:

SELECT Item_Name,
    SUM(Case WHEN Type='Like' THEN Amount ELSE 0 END) AS Like_Amount,
    SUM(Case WHEN Type='Love' THEN Amount ELSE 0 END) AS Love_Amount,
    SUM(Case WHEN Type='Ours' THEN Amount ELSE 0 END) AS Ours_Amount,
    SUM(Case WHEN Type='Like' THEN Qty ELSE 0 END) AS Like_Qty,
    SUM(Case WHEN Type='Love' THEN Qty ELSE 0 END) AS Love_Qty,
    SUM(Case WHEN Type='Ours' THEN Qty ELSE 0 END) AS Ours_Qty
FROM table1
GROUP BY Item_Name
ORDER BY Item_Name

如果Type列中的可能值列表已修复,则上述查询有效。如果这些值可以更改,则需要使用其他方法(例如PIVOT