带条件的SQL SUM

时间:2017-03-13 19:17:16

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

+--------+--------+-------+-------+
| PartId | ItemId | Price | Staus |
+--------+--------+-------+-------+
|  94669 |   3678 |    88 |     1 |
|  94669 |   3679 |    22 |     1 |
|  94669 |   3680 |    30 |     1 |
|  94669 |   3681 |    50 |     4 |
|  94670 |   3678 |    88 |     1 |
|  94670 |   3679 |    22 |     1 |
|  94670 |   3680 |    30 |     1 |
|  94670 |   3681 |    50 |     1 |
+--------+--------+-------+-------+

预期输出为(无状态4)

+--------+------------+
| PartId | TotalPrice |
+--------+------------+
|  94669 |        140 |
|  94670 |        190 |
+--------+------------+

如何在SQL中实现这一目标?

2 个答案:

答案 0 :(得分:4)

使用wheregroup by的非常基本的聚合查询。

select partid, sum(price) as totalprice
from t
where [status] <> 4
group by partid

如果您必须省略{1}}而不是1,那么使用status代替是正确的:

status = 1

答案 1 :(得分:1)

您可以尝试:

SELECT "Part ID", SUM(Price)
FROM (
    SELECT "Part ID", Price
    FROM Table
    WHERE Status <> 4)
GROUP BY "Part ID";