Search code examples
sqlsql-servergroup-byhaving

SQL identify records which occur more than certain months


I'm trying to identify members who have more than 4 months of claims for any single procedure code. Below is the SQL code that I tried. I'm not sure if that is right.

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 Code

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

SQL example


Solution

  • If you want members where the procedure code appears in more than 4 months, you can use count(distinct):

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