1

我有一份人们出院的地方的清单,我需要按年龄对他们进行分层。我目前在下面的查询有效,但它列出了每个年龄的每个放电类型计数。 在此处输入图像描述

您可以查看 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)
4

4 回答 4

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
于 2012-05-02T13:23:16.970 回答
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;
于 2012-05-02T13:23:26.483 回答
1

删除所选内容和 Group by 部分中的 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)
于 2012-05-02T13:24:04.330 回答
0

SELECT只需从和 中删除年龄计算GROUP BY,然后将 更改HAVING为 a 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
于 2012-05-02T13:22:51.680 回答