使用UNION重复值

时间:2014-10-15 01:34:48

标签: sql postgresql

我在下面有这个查询,我在使用UNION时遇到了麻烦,它复制了purok

SELECT h.cpurok as purok,
COUNT(m.cgender) AS total,
SUM(CASE WHEN m.cgender::text = 'Male'::text THEN 1 ELSE 0 END) AS male, 
SUM(CASE WHEN m.cgender::text = 'Female'::text THEN 1 ELSE 0 END) AS female
FROM tbl_member as m, tbl_household as h, tbl_barangay as b, tbl_answer as a
WHERE h.chholdnumber=m.chholdnumber 
and h.cbrgycode=b.cbrgycode 
and b.cbrgyname='AGAO' 
and a.nqid=16 
and a.nmemberid=m.nmemberid
and choice in ('29','30','31','32','35','36')
GROUP BY purok 
UNION
SELECT h.cpurok as purok,
0 AS total, 0 AS male, 0 AS female
FROM tbl_household as h, tbl_answer as a
WHERE a.nqid=15
and choice='21'
order by purok

输出正常,只想删除purok0total,male,female的重复{{1}}。

output of the query above

应删除上图中标记的红色。

1 个答案:

答案 0 :(得分:2)

Union使行(而非单个键)成为唯一的。在您的情况下,您有两个不同的行 - 01, 2, 2, 001, 0, 0, 0,因此UNION会保留这两行。

您可能在表级别上UNION ALL,将其包含在GROUP BY的大purok个查询中:

SELECT purok,
SUM(num) AS total,
SUM(male) AS male, 
SUM(female) AS female
FROM (

    SELECT
        h.cpurok AS
    ,   1 AS num
    ,   CASE WHEN m.cgender::text = 'Male'::text THEN 1 ELSE 0 END AS male
    ,   CASE WHEN m.cgender::text = 'Female'::text THEN 1 ELSE 0 END AS female
    FROM tbl_member as m
    JOIN tbl_household as h ON h.chholdnumber=m.chholdnumber
    JOIN tbl_barangay as b ON h.cbrgycode=b.cbrgycode AND b.cbrgyname='AGAO'
    JOIN tbl_answer as a ON a.nmemberid=m.nmemberid AND a.nqid=16
    WHERE choice in ('29','30','31','32','35','36')

    UNION ALL

    SELECT h.cpurok as purok,
    0 AS num, 0 AS male, 0 AS female
    FROM tbl_household as h
    JOIN tbl_answer as a ON h.householdid=a.householdid AND a.nqid=15
    WHERE choice='21'
) raw
GROUP BY purok 
ORDER BY purok

注意:您的查询未加入tbl_household tbl_answer,因此我“发明了”占位符加入条件h.householdid=a.householdid。您需要将其替换为实际的连接标准。