我列出了人们已经出院的地方,我需要按年龄对他们进行分层。我目前在下面的查询工作,但它列出了每个年龄的每个排放类型计数。
你可以看到0-1-2-3岁如何根据年龄分别计算排出类型。如何才能使它只有dischargeType
和列出的计数(只要它们是18及以下)
SELECT DATEDIFF(yyyy, tblVisits.dob, tblVisits.admitdate) AS Age, tblDischarge.dischargeType, COUNT(tblDischarge.dischargeType) AS COUNTS
FROM tblVisits INNER JOIN
tblDischarge ON tblVisitsDischargeStatus = tblDischarge.dis_statID
GROUP BY DATEDIFF(yyyy,tblVisits.dob, tblVisits.Admitdate), tblDischarge.dischargeType
HAVING (DATEDIFF(yyyy,tblVisits.DOB, tblVisits.AdmitDate) <=18)
答案 0 :(得分:1)
如果你只是想要18岁以下的人,但每个出院型只有一排......
SELECT
tblDischarge.dischargeType,
COUNT(tblDischarge.dischargeType) AS COUNTS
FROM
tblVisits
INNER JOIN
tblDischarge
ON tblVisitsDischargeStatus = tblDischarge.dis_statID
WHERE
(DATEDIFF(yyyy,tblVisits.DOB, tblVisits.AdmitDate) <=18)
GROUP BY
tblDischarge.dischargeType
如果你想把年龄分组到分层......
SELECT
tblDischarge.dischargeType,
CASE DATEDIFF(yyyy,tblVisits.DOB, tblVisits.AdmitDate)
WHEN <= 3 THEN '0..3'
WHEN <= 8 THEN '4..8'
WHEN <= 12 THEN '9..12'
ELSE '13..18'
END AS ageBand,
COUNT(tblDischarge.dischargeType) AS COUNTS
FROM
tblVisits
INNER JOIN
tblDischarge
ON tblVisitsDischargeStatus = tblDischarge.dis_statID
WHERE
(DATEDIFF(yyyy,tblVisits.DOB, tblVisits.AdmitDate) <=18)
GROUP BY
tblDischarge.dischargeType,
CASE DATEDIFF(yyyy,tblVisits.DOB, tblVisits.AdmitDate)
WHEN <= 3 THEN '0..3'
WHEN <= 8 THEN '4..8'
WHEN <= 12 THEN '9..12'
ELSE '13..18'
END
答案 1 :(得分:1)
我不确定您的问题,但如果您只想按dischargeType
计算,对于所有18岁以下的人,代码如下:
SELECT dis.dischargeType, COUNT(dis.dischargeType) AS COUNTS
FROM tblDischarge dis
JOIN tblVisits vst ON vst.DischargeStatus = dis.dis_statID
WHERE (DATEDIFF(yyyy,vst.DOB, vst.AdmitDate) <= 18)
GROUP BY dis.dischargeType;
或者您可以使用子查询,例如:
SELECT dischargeType, COUNT(dischargeType) AS COUNTS
FROM tblDischarge
WHERE dis_statID IN (
SELECT vst.DischargeStatus
FROM tblVisits vst
WHERE (DATEDIFF(yyyy, vst.DOB, vst.AdmitDate) <= 18)
)
GROUP BY dis.dischargeType;
答案 2 :(得分:1)
删除选择中的AGE和按部分分组:
SELECT tblDischarge.dischargeType, COUNT(tblDischarge.dischargeType) AS COUNTS
FROM tblVisits INNER JOIN
tblDischarge ON tblVisitsDischargeStatus = tblDischarge.dis_statID
GROUP BY tblDischarge.dischargeType
HAVING (DATEDIFF(yyyy,tblVisits.DOB, tblVisits.AdmitDate) <=18)
答案 3 :(得分:0)
只需从SELECT
和GROUP BY
中移除年龄计算,然后将HAVING
更改为WHERE
:
SELECT tblDischarge.dischargeType,
COUNT(tblDischarge.dischargeType) as COUNTS
FROM tblVisits
INNER JOIN tblDischarge
ON tblVisitsDischargeStatus = tblDischarge.dis_statID
WHERE (DATEDIFF(yyyy,tblVisits.DOB, tblVisits.AdmitDate) <=18)
GROUP BY tblDischarge.dischargeType