我有这个tbl_religion和fieldname creldesc
带有这些字段的
和tbl_member
我有这个查询来计算tbl_member中所有现有的宗教信仰,并且还算不上。那个宗教的男性和女性因此我提出了这个问题:
SELECT m.creldesc as type,
COUNT(m.creldesc) as total,
SUM(CASE WHEN m.cgender='Male' THEN 1 ELSE 0 END) as male,
SUM(CASE WHEN m.cgender='Female' THEN 1 ELSE 0 END) as female
FROM tbl_member as m, tbl_barangay as b, tbl_household as h
WHERE m.chholdnumber = h.chholdnumber and h.cbrgycode=b.cbrgycode and b.cbrgyname = 'AGAO'
and m.crelationdesc !='Brgy. Captain'
GROUP BY m.creldesc
ORDER BY tot DESC;
并获得此输出:
我想要实现的还是显示来自tbl_religion的剩余宗教,其中0为值。我做了一个左连接,但得到一个错误。有人可以帮助我,我怎么能做到这一点?
type total male female
Roman Catholic 7 4 3
Baptist 3 1 2
Islam 3 3 0
Iglesia ni Cristo 1 1 0
Free Methodist 1 1 0
Ang Dating Daan 1 0 1
Aglipay/Filipinsta 0 0 0
All the Gospel 0 0 0
Alpha Omega 0 0 0
and so on.............................
答案 0 :(得分:0)
对所有表使用相同的连接方法,如下所示:
SELECT m.creldesc as type, COUNT(m.creldesc) as tot,
SUM(CASE WHEN m.cgender='Male' THEN 1 ELSE 0 END) as male,
SUM(CASE WHEN m.cgender='Female' THEN 1 ELSE 0 END) as female
FROM tbl_religion
LEFT JOIN tbl_member as m
ON tbl_religion.creldesc=m.creldesc
LEFT JOIN tbl_household as h
ON m.chholdnumber = h.chholdnumber
LEFT JOIN tbl_barangay as b
ON h.cbrgycode=b.cbrgycode
WHERE b.cbrgyname = 'AGAO' AND m.crelationdesc !='Brgy. Captain'
GROUP BY m.creldesc
ORDER BY tot DESC
... FROM tbl_member, tbl_barangay, tbl_household LEFT JOIN tbl_religion ...
的当前查询方法错误,会产生语法错误。
答案 1 :(得分:0)
你无法做到这一点:
FROM @ TABLE1,@ TABLE2,@ TABLE3
LEFT JOIN @ TABLE0 ON ...
您可以一次只从一张桌子中选择项目...加入相同。
SELECT m.creldesc as type,
COUNT(m.creldesc) as tot,
SUM(CASE WHEN m.cgender='Male' THEN 1 ELSE 0 END) as male,
SUM(CASE WHEN m.cgender='Female' THEN 1 ELSE 0 END) as female
FROM tbl_member as m
LEFT JOIN tbl_religion z ON z.creldesc = m.creldesc
LEFT JOIN tbl_barangay h ON h.cbrgycode=b.cbrgycode
SO ON.... WITH JOINS
GROUP BY m.creldesc
更新作业代码:
SELECT m.creldesc as type, COUNT(m.creldesc) as tot, SUM(CASE WHEN m.cgender='Male' THEN 1 ELSE 0 END) as male,
SUM(CASE WHEN m.cgender='Female' THEN 1 ELSE 0 END) as female
FROM tbl_member as m
LEFT JOIN tbl_religion r ON r.creldesc = m.creldesc
LEFT JOIN tbl_barangay as b ON m.chholdnumber = b.cbrgycode
LEFT JOIN tbl_household as h ON h.cbrgycode = b.cbrgycode
WHERE b.cbrgyname = 'AGAO' and m.crelationdesc !='Brgy. Captain'
GROUP BY m.creldesc
ORDER BY tot DESC
答案 2 :(得分:0)
这就是我的所作所为:
SELECT tbl_member.creldesc AS type,
COUNT(tbl_member.creldesc) AS total,
SUM(CASE WHEN tbl_member.cgender::text = 'Male'::text THEN 1 ELSE 0 END) AS male,
SUM(CASE WHEN tbl_member.cgender::text = 'Female'::text THEN 1 ELSE 0 END) AS female
FROM tbl_member
GROUP BY tbl_member.creldesc
UNION
SELECT b.creldesc AS type, 0 AS total, 0 AS male, 0 AS female
FROM tbl_religion b
WHERE NOT (b.creldesc::text IN
( SELECT DISTINCT tbl_member.creldesc FROM tbl_member))
GROUP BY b.creldesc;
这是它的输出:
全部:)我使用了UNION而不是LEFT JOIN。