2

嗨,我在 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

我想计算在 01-05-2013 到 18-07-2013 之间clientid的最高值为2的 1007 有多少个案例alert_val

就像在这种情况下它:

case id:1,caseid:3
4

2 回答 2

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

输出:

| 案例ID |
----------
| 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

输出:

| 总计 |
---------
| 2 |

这是SQLFiddle演示

于 2013-07-26T03:41:35.083 回答
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'
于 2013-07-26T03:48:01.033 回答