选择不同于多列及其匹配值总和

时间:2014-06-01 18:14:42

标签: sql sql-server tsql

我有一个名为Orders的表。 表格的每一行代表客户的订单。

prod 表示产品

+-----------------------------------------------------------------------------------+
| prod_1      | prod_1_qty  | prod_2      |prod_2_qty   | prod_3      | prod_3_qty  |
|-------------------------------------------------------|---------------------------|
| chair       | 3           | board       |9            | bed         |4            |
| board       | 8           | door        |2            | desk        |2            |
| chair       | 2           | window      |1            | door        |6            |
| desk        | 4           | chair       |3            | sofa        |1            |

我想写一个查询,返回每个product订购的数量,如下所示:

+---------------------------+
| product     | product_qty |
|---------------------------|
| chair       | 8           |
| board       | 17          |
| door        | 8           |
| window      | 1           |
| sofa        | 1           |
| bed         | 4           |
| desk        | 6           |

有没有办法使用T-SQL来实现这一目标,如果有,那么用于执行此操作的查询是什么?

1 个答案:

答案 0 :(得分:3)

SELECT x.prod
     , SUM(x.prod_qty) AS total
FROM (
       SELECT prod1 AS prod, prod_qty AS total FROM table
          UNION ALL
       SELECT prod2 AS prod, prod_qty AS total FROM table 
          UNION ALL
       SELECT prod3 AS prod, prod_qty AS total FROM table
     ) x 
GROUP BY x.prod