[英]Select distinct from multiple columns and its matching values sum
I have this table named Orders
. 我有名为Orders
表。 Each row of the table represents an order made by a customer. 表格的每一行代表客户的订单。
prod means product 产品表示产品
+-----------------------------------------------------------------------------------+
| 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 |
I would like to write a query that returns the quantity of each product
ordered like this: 我想编写一个查询来返回订购的每种product
的数量,如下所示:
+---------------------------+
| product | product_qty |
|---------------------------|
| chair | 8 |
| board | 17 |
| door | 8 |
| window | 1 |
| sofa | 1 |
| bed | 4 |
| desk | 6 |
Is there any way to achieve this using T-SQL
, and if so, what is the query one would use to do this? 有什么方法可以使用T-SQL
来实现这一目标,如果是的话,执行此操作的查询将是什么?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.