我正在尝试在汇总数据时消除重复项。
CREATE TABLE abc
( dt DATE FORMAT 'YYYY-MM-DD'
,acct NUMBER
,chk_lmt VARCHAR(10)
,baln_lmt VARCHAR(10)
,wk DATE FORMAT 'YYYY-MM-DD'
) ;
INSERT INTO abc
('2018-03-19' , 1001, 'under 1000' , 'under 500', '2018-03-23');
INSERT INTO abc
('2018-03-20' , 1001, 'under 1000' , 'under 500', '2018-03-23');
INSERT INTO abc
('2018-03-20' , 1002, 'under 1000' , 'under 500', '2018-03-23');
SELECT dt,wk,'chk_lmt_chk' AS TYPEs,
SUM ( CASE WHEN chk_lmt = 'under 1000' THEN 1 ELSE 0 END ) AS counts
FROM abc
GROUP BY 1,2,3;
dt wk TYPEs counts
19/03/2018 23/03/2018 chk_lmt_chk 1
19/03/2018 23/03/2018 chk_lmt_chk 0
20/03/2018 23/03/2018 chk_lmt_chk 2
对于dt 20/03/2018,计数应为1,因为该指令已在19/03/2018中捕获。
有什么想法吗?
由于
答案 0 :(得分:1)
这是对原始问题的回答。
如果您希望帐户只计算一次,请第一次使用row_number()
:
SELECT dt, wk, 'chk_lmt_chk' AS TYPEs,
SUM(CASE WHEN chk_lmt = 'under 1000' THEN 1 ELSE 0 END) AS counts
FROM (SELECT abc.*,
ROW_NUMBER() OVER (PARTITION BY acct ORDER BY dt) as seqnum
FROM ptemp.abc
) abc
WHERE seqnum = 1
GROUP BY 1, 2, 3;