我有这张桌子:
DATE REGCODE1 REGCODE2 REGCODE 3 REGCODE4
02/01/15 70771 60771 40771 30771
02/01/15 null 60775 null null
02/01/15 70855 null 40771 null
02/01/15 null null null null
03/01/15 70771 55002 66554 66555
03/01/15 70772 55002 65557 66555
05/01/15 null 55002 57777 30771
05/01/15 70855 null null null
05/01/15 70826 null null 9
我需要按日期统计不同的REGCODEs
分组,但是如果其中一个在上一个日期重复,则不再计算
所以,我需要这样的东西:
DATE COUNT(REGCODE1) COUNT(REGCODE2) COUNT(REGCODE3) COUNT(REGCODE4)
02/01/15 2 2 1 1
03/01/15 1 1 2 1
05/01/15 1 0 1 1
非常感谢你的帮助。
答案 0 :(得分:0)
您只计算一次注册码 - 最早的日期。首先删除regcode重复项,然后按日期排除第二步。像这样:
SELECT "DATE", count(*)
FROM (SELECT "REGCODE1", min("DATE") as "DATE"
FROM regcodes
WHERE "REGCODE1" IS NOT NULL
GROUP BY "REGCODE1")
GROUP BY "DATE"
ORDER BY "DATE";
这仅适用于单个注册码,您必须加入此类型的4个子查询才能获得所需的结果:
SELECT "DATE", count("REGCODE1"), count("REGCODE2"), count("REGCODE3"), count("REGCODE4")
FROM (SELECT min("DATE") as "DATE", "REGCODE1", NULL AS "REGCODE2", NULL AS "REGCODE3", NULL AS "REGCODE4"
FROM regcodes WHERE "REGCODE1" IS NOT NULL GROUP BY "REGCODE1"
UNION ALL
SELECT min("DATE") as "DATE", NULL, "REGCODE2", NULL, NULL
FROM regcodes WHERE "REGCODE2" IS NOT NULL GROUP BY "REGCODE2"
UNION ALL
SELECT min("DATE") as "DATE", NULL, NULL, "REGCODE3", NULL
FROM regcodes WHERE "REGCODE3" IS NOT NULL GROUP BY "REGCODE3"
UNION ALL
SELECT min("DATE") as "DATE", NULL, NULL, NULL, "REGCODE4"
FROM regcodes WHERE "REGCODE4" IS NOT NULL GROUP BY "REGCODE4")
GROUP BY "DATE"
ORDER BY "DATE";
这是SQLFiddle。