Postgres - 获取另一列条件下列中值的总和

时间:2017-03-12 19:34:01

标签: sql postgresql

我在Postgres中有一个表(custdata),如下所示:

customerid | mID | count
    1         3      13
    1         2      17
    1         2       3
    1         5      14
    1         4       7

这样的查询:

SELECT
c.customerid,
c.mID,
c.count,
SUM (c.count)
FROM custdata c
JOIN tableB b
ON b.customerid = c.customerid
WHERE c.mID <> 2
AND b.starttimestamp = ? and b.endtimestamp = ?

我想获得count不等于2的值的mID列中的值的总和。在这种情况下,正确的总和将是34.但在我的情况下,结果是返回2个不正确的总和。如何获取count列中mID不是2的值的总和?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

希望,我理解正确。 请查看以下查询

SELECT
c.customerid,
c.mID,
c.count,
SUM(case when c.mID<>2 then  c.count else 0  end) over(partition by c.customerid order by c.customerid) sum_col
FROM custdata c
JOIN tableB b
ON b.customerid = c.customerid
WHERE
--c.mID <> 2 AND
b.starttimestamp = ? and b.endtimestamp = ?

答案 1 :(得分:0)

使用窗口功能,您可以使用customerID进行分组:

SELECT
c.customerid,
c.mID,
c.count,
SUM(c.count) over(partition by c.customerid)
FROM custdata c
JOIN tableB b using(customerid)
WHERE c.mID <> 2
group by c.customerid,
c.mID,
c.count