Sum列作为附加列sql

时间:2018-03-02 03:08:02

标签: sql

我正在尝试使用具有不同列的数据集。我正在寻找添加一个列,该列根据订单ID提供每行的数量总和。请参阅下面的输入和所需输出:

输入:

+----+---------+-----+----------+
| ID | OrderID | PID | Quantity |
+----+---------+-----+----------+
| 1  | 10248   | 11  | 12       |
+----+---------+-----+----------+
| 2  | 10248   | 42  | 10       |
+----+---------+-----+----------+
| 3  | 10248   | 72  | 5        |
+----+---------+-----+----------+
| 4  | 10249   | 14  | 9        |
+----+---------+-----+----------+
| 5  | 10249   | 51  | 40       |
+----+---------+-----+----------+
| 6  | 10250   | 41  | 10       |
+----+---------+-----+----------+
| 7  | 10250   | 51  | 35       |
+----+---------+-----+----------+
| 8  | 10250   | 65  | 15       |
+----+---------+-----+----------+
| 9  | 10251   | 22  | 6        |
+----+---------+-----+----------+
| 10 | 10251   | 57  | 15       |
+----+---------+-----+----------+
| 11 | 10251   | 65  | 20       |
+----+---------+-----+----------+
| 12 | 10252   | 20  | 40       |
+----+---------+-----+----------+
| 13 | 10252   | 33  | 25       |
+----+---------+-----+----------+

期望的输出:

+----+---------+-----+----------+-------+
| ID | OrderID | PID | Quantity | Total |
+----+---------+-----+----------+-------+
| 1  | 10248   | 11  | 12       | 27    |
+----+---------+-----+----------+-------+
| 2  | 10248   | 42  | 10       | 27    |
+----+---------+-----+----------+-------+
| 3  | 10248   | 72  | 5        | 27    |
+----+---------+-----+----------+-------+
| 4  | 10249   | 14  | 9        | 49    |
+----+---------+-----+----------+-------+
| 5  | 10249   | 51  | 40       | 49    |
+----+---------+-----+----------+-------+
| 6  | 10250   | 41  | 10       | 60    |
+----+---------+-----+----------+-------+
| 7  | 10250   | 51  | 35       | 60    |
+----+---------+-----+----------+-------+
| 8  | 10250   | 65  | 15       | 60    |
+----+---------+-----+----------+-------+
| 9  | 10251   | 22  | 6        | 41    |
+----+---------+-----+----------+-------+
| 10 | 10251   | 57  | 15       | 41    |
+----+---------+-----+----------+-------+
| 11 | 10251   | 65  | 20       | 41    |
+----+---------+-----+----------+-------+
| 12 | 10252   | 20  | 40       | 65    |
+----+---------+-----+----------+-------+
| 13 | 10252   | 33  | 25       | 65    |
+----+---------+-----+----------+-------+

2 个答案:

答案 0 :(得分:1)

由于您没有提及任何RDBMS,因此下面的查询几乎可以在大多数RDBMS中使用。查询的作用是计算子查询中的Total并将结果连接到原始表本身。

SELECT  a.*,
        b.Total
FROM    TableName a
        INNER JOIN
        (
            SELECT  OrderID, SUM(Quantity) Total
            FROM    TableName
            GROUP   BY OrderID
        ) b ON a.OrderID = b.OrderID

这里是Demo

但是,如果您的RDBMS支持SUM() OVER()等窗口函数,则可以简单地将其写为

SELECT  a.*,
        SUM(Quantity) OVER (PARTITION BY OrderID) Total
FROM    TableName a

这里是Demo

答案 1 :(得分:0)

使用GROUP BY

尝试:

SELECT OrderID, COUNT(quantity) as total FROM table GROUP BY OrderID;