SQL识别发生在某些月份以上的记录

时间:2019-02-09 22:04:36

标签: sql sql-server group-by having

我正在尝试确定对任何单个过程代码的索赔超过4个月的成员。下面是我尝试过的SQL代码。我不确定这是否正确。

表格

+-------------+---------------+-----------+------------+
| ServiceDate | ProcedureCode | MemberId  | Claim_Nbr  |
+-------------+---------------+-----------+------------+
| 2018-01-15  | K800          | 364882903 | 1600235465 |
+-------------+---------------+-----------+------------+
| 2018-02-15  | K800          | 364882903 | 1607478399 |
+-------------+---------------+-----------+------------+
| 2018-01-15  | K800          | 388299399 | 4589992948 |
+-------------+---------------+-----------+------------+
| 2018-03-15  | K800          | 364882903 | 1600489300 |
+-------------+---------------+-----------+------------+
| 2018-04-15  | K800          | 364882903 | 1600388289 |
+-------------+---------------+-----------+------------+
| 2018-05-15  | K800          | 364882903 | 1600028848 |
+-------------+---------------+-----------+------------+
| 2018-06-15  | K800          | 364882903 | 1600894889 |
+-------------+---------------+-----------+------------+
| 2018-07-15  | K800          | 364882903 | 1600023884 |
+-------------+---------------+-----------+------------+
| 2018-07-15  | K800          | 364882903 | 1600934888 |
+-------------+---------------+-----------+------------+
| 2018-02-15  | K800          | 388299399 | 3774999999 |
+-------------+---------------+-----------+------------+
| 2018-03-15  | K800          | 388299399 | 9498378489 |
+-------------+---------------+-----------+------------+

SQL代码

SELECT ProcedureCode, MemberId FROM CLAIMS
GROUP BY ProcedureCode
HAVING SUM(Month(ServiceDate))>4

SQL example

1 个答案:

答案 0 :(得分:1)

如果希望成员在4个月以上的时间内出现程序代码,则可以使用count(distinct)

select memberId, procedureCode
from claims
group by memberId, procedureCode
having count(distinct year(ServiceDate) * 100 + month(ServiceDate)) > 4;