SQL 识别出现超过特定月份的记录

SQL identify records which occur more than certain months

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

Table

+-------------+---------------+-----------+------------+
| 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

如果您想要程序代码出现在4个月以上的会员,您可以使用count(distinct):

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