嗨,我在SQL中遇到了如下情况:
表名:case_details
caseid refno clientid report_date
1 1/1 1007 08-05-2013
2 1/2 1007 01-06-2013
3 1/3 1007 12-07-2013
4 1/4 1012 17-07-13
5 1/6 1009 08-07-13
表名:
case_check_detail
caseid checkid alert_val
1 1 1
1 2 2
1 3 1
1 4 2
2 5 4
2 6 3
2 7 2
2 8 1
3 9 2
3 10 1
3 11 2
3 12 1
4 13 3
4 14 3
4 15 3
4 16 4
5 17 1
5 18 2
5 19 1
5 20 2
我想计算一下在2013年5月1日至2013年7月18日期间,
clientid
1007的病例有多少,其中alert_val
的最高值是2就像在这种情况下:
case id:1,caseid:3
最佳答案
试用
SELECT d.caseid
FROM case_details d JOIN case_check_detail c
ON d.caseid = c.caseid
WHERE d.clientid = 1007
AND d.report_date BETWEEN '20130501' AND '20130718'
GROUP BY d.caseid
HAVING MAX(c.alert_val) = 2
输出:
| CASEID | ---------- | 1 | | 3 |
If you want to count them
SELECT COUNT(*) total
FROM
(
SELECT d.caseid
FROM case_details d JOIN case_check_detail c
ON d.caseid = c.caseid
WHERE d.clientid = 1007
AND d.report_date BETWEEN '20130501' AND '20130718'
GROUP BY d.caseid
HAVING MAX(c.alert_val) = 2
) q
输出:
|总计|
—————-
| 2个|
这里是SQLFiddle演示
关于sql - SQL查询以获取数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17872442/