数据库:SQL Fiddle
需要查询:返回每家保险公司25-35岁的女性和男性人数。
我的进步:
CREATE VIEW MenInAge AS
SELECT p.pname,p.pid,p.cid
FROM Patient p
WHERE p.gender = 'm' and p.age between 25 and 35;
CREATE VIEW WomenInAge AS
SELECT p.pname,p.pid,p.cid
FROM Patient p
WHERE p.gender = 'f' and p.age between 25 and 35;
CREATE VIEW MenInAgeCount AS
SELECT m.cid, COUNT(m.pid) as c
FROM MenInAge m
GROUP BY m.cid;
CREATE VIEW WomenInAgeCount AS
SELECT w.cid, COUNT(w.pid) as c
FROM WomenInAge w
GROUP BY w.cid;
如何为每个InsuranceCompany.cid显示WomenInAgeCount.c和MenInAgeCount.c列?
答案 0 :(得分:4)
解释:
您必须使用 LEFT OUTER JOIN 加入表格InsuranceCompanies
和Patient
,方法是加入两个表格中cid
列的记录,并同时应用过滤以仅选择年龄 25 和 35 (包括那些边界值)的患者。 CASE 语句仅检查患者是男性还是女性,并通过在值匹配时分配值1来计算两个不同的列,如果值不匹配则分配0。最后,您必须按cname对结果进行分组,以便按保险公司名称获取计数。
有关CASE的说明:
在CASE表达式中,查询说明WHEN性别字段值 f 为列 female 分配值1.值1是硬编码的,因为它表示查询找到1行匹配gender ='f'记录,这也代表1个人。您也可以声明ELSE 0,但它是隐式的,因此没有必要指定它。此CASE表达式计算查询结果中的每条记录。 Finanlly,你将获得包含1或0的女性专栏的所有行。当你将这一列与女性相加时,你将获得女性的总数,男性专栏的逻辑相同。
COALESCE
这里用第二个参数中的给定值替换任何NULL值(在这种情况下为零)。
Click here to view the demo in SQL Fiddle.
脚本:
SELECT ic.cname
, COALESCE(SUM(CASE WHEN gender = 'f' THEN 1 END), 0) female
, COALESCE(SUM(CASE WHEN gender = 'm' THEN 1 END), 0) male
FROM InsuranceCompanies ic
LEFT OUTER JOIN Patient p
ON p.cid = ic.cid
AND age BETWEEN 25 AND 35
GROUP BY ic.cname;
输出:
CNAME FEMALE MALE
---------- ------ ----
Clalit Inc 0 2
Harel Inc 2 0
Click here to view the demo in SQL Fiddle
脚本:
SELECT ic.cname
, SUM(CASE WHEN gender = 'f' THEN 1 END) female
, SUM(CASE WHEN gender = 'm' THEN 1 END) male
FROM InsuranceCompanies ic
LEFT OUTER JOIN Patient p
ON p.cid = ic.cid
AND age BETWEEN 25 AND 35
GROUP BY ic.cname;
输出:
CNAME FEMALE MALE
---------- ------ ----
Clalit Inc NULL 2
Harel Inc 2 NULL
答案 1 :(得分:0)
JOIN怎么样?
SELECT I.cname, ISNULL(W.c,0) AS WomenCount, ISNULL(M.c,0) as MenCount
FROM InsuranceCompanies AS I
LEFT JOIN MenInAgeCount AS M ON M.cid = I.cid
LEFT JOIN WomenInAgeCount AS W ON W.cid = I.cid
LEFT JOIN
此处以防于男性或女性视图中不包含InsuranceCompanies表中每行的条目。 ISNULL
适用于SQL Server,但您可以根据需要修改MySQL,Oracle。
答案 2 :(得分:0)
这应该会给你一些帮助 -
select count(pid) as numPatients, cid, gender
from patient
group by cid, gender