嗨我在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
我想计算clientid
1007在{2013年5月1日至2013年7月18日期间alert_val
的最高值为2的案例数
就像在这种情况下一样:
case id:1,caseid:3
答案 0 :(得分:1)
尝试
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 |
如果你想算数
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
输出:
| TOTAL | --------- | 2 |
这是 SQLFiddle 演示
答案 1 :(得分:0)
SELECT COUNT(*)
FROM case_check_detail AS ccd
JOIN case_details AS cd ON cd.caseid=ccd.caseid
WHERE alert_val=2 AND report_date BETWEEN '2013-05-01' AND '2013-07-18'