我在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的值的总和?任何帮助将不胜感激。
答案 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