所以我有一张桌子dpgift。我需要根据表格生成24种不同的“统计数据”(计数和与过滤器的总和)。
下面应该生成前三列。
select a.lc as listCode, a.c, NVL(b.c,0), NVL(c.c,0)
FROM (select list_code as lc, count(donor) as c
FROM dpgift
group by list_code) a
LEFT JOIN (select list_code as lc, count(donor) as c
FROM dpgift
WHERE dpgift.rectype="P"
group by list_code) b
LEFT JOIN (select list_code as lc, count(donor) as c
FROM dpgift
WHERE dpgift.rectype="G"
group by list_code) c
ON b.lc = c.lc
ON a.lc = b.lc
这几乎可以正常工作但是我的连接出了问题。第三列(c.c)只有b.c不为空的值。
有人可以告诉我出了什么问题吗?
顺便说一句,我在VFP工作,但是sql似乎非常标准。编辑:好的,这是我得到的输出
listcode c exp_3 Exp_4
482 14 0 0
483 2 0 0
499 852 1 857
....
应该是:
listcode c exp_3 Exp_4
482 14 0 14
483 2 0 2
499 852 1 857
....
答案 0 :(得分:4)
这个版本应该能够产生你想要的东西。
SELECT list_code,
COUNT(donor),
SUM(CASE WHEN rectype = 'P' THEN 1 ELSE 0 END) AS Pcount,
SUM(CASE WHEN rectype = 'G' THEN 1 ELSE 0 END) AS Gcount
FROM dpgift
GROUP BY list_code