SQL识别同一年中发生多次的记录

时间:2019-02-12 17:22:48

标签: sql sql-server group-by

我有一条记录,每位成员每年仅应从中记录一组过程代码。我正在尝试找出违反此规则的情况。 我试过下面的SQL,是正确的吗?

表格

+---------------+--------+-------------+
| ProcedureCode | Member | ServiceDate |
+---------------+--------+-------------+
| G0443         | 1234   | 01-03-2017  |
+---------------+--------+-------------+
| G0443         | 1234   | 05-03-2018  |
+---------------+--------+-------------+
| G0443         | 1234   | 07-03-2018  |
+---------------+--------+-------------+
| G0444         | 3453   | 01-03-2017  |
+---------------+--------+-------------+
| G0443         | 5676   | 07-03-2018  |
+---------------+--------+-------------+

违反规则的预期结果

+---------------+--------+
| ProcedureCode | Member |
+---------------+--------+
| G0443         | 1234   |
+---------------+--------+

SQL

Select ProcedureCD, Mbr_Id
From CLAIMS
Where ProcedureCD IN ('G0443', 'G0444')
GROUP BY ProcedureCD,Mbr_Id, YEAR(ServiceFromDate)
having count(YEAR(ServiceFromDate))>1

3 个答案:

答案 0 :(得分:1)

Select ProcedureCode, Member,YEAR(ServiceDate) [Year],Count(*) Occurences
From CLAIMS 
Where ProcedureCode IN ('G0443', 'G0444')
GROUP BY ProcedureCode, Member,YEAR(ServiceDate)
HAVING Count(*) > 1

答案 1 :(得分:1)

您编写的查询将起作用(如果您更正了列名-您的查询使用与您发布的示例数据不同的列名)。通过在COUNT(*)子句中使用HAVING可以在视觉上进行简化。 COUNT对任何非null值有效,非null累积1,null累积0,但是在这种情况下,在计数内使用YEAR没有任何意义,因为所有日期都不为null,并且count对值-count(*), count(1), count(0), count(member)在这里将同样有效

count(column)count(*)的唯一不同之处在于column包含空值。还有一个COUNT选项,您可以将DISTINCT放在方括号内,这将导致计数忽略重复的值。

在包含6行值1, 1, 2, null, 3, 3的表列上的

COUNT DISTINCT将返回3(3个唯一值)。计数同一列将返回5(5个非空值),COUNT(*)将返回6

您应该理解,通过将YEAR(...)放在“ by by”组中而不是“ select”组中,您可能会在输出中产生重复的行。例如,如果您还具有以下行:

 Member, Code, Date
1234, G0443, 1-1-19
1234, G0443, 2-1-19

您正在按年份分组(但未显示),那么您会看到:

1234, G0443    --it's for year 2018
1234, G0443    --it's for year 2019

我个人认为在选择列表中显示年份会很方便,因此可以更好地查明问题所在,但是如果要压缩这些重复的行,请执行SELECT DISTINCT或者,利用之间的差异计算并计数不同:从GROUP BY中删除年份,而改为说HAVING COUNT(*) > COUNT(DISTINCT YEAR(ServiceDate))

如上所述,如果年份重复,则count(*)将大于不同年份的计数

答案 2 :(得分:1)

希望此代码对您有帮助

create table  #temp (ProcedureCode varchar(20),Member varchar(20),ServiceDate Date)
insert into #temp (ProcedureCode,Member,ServiceDate) values ('G0443','1234','01-03-2017')
insert into #temp (ProcedureCode,Member,ServiceDate) values ('G0443','1234','05-03-2018 ')
insert into #temp (ProcedureCode,Member,ServiceDate) values ('G0443','1234','07-03-2018')
insert into #temp (ProcedureCode,Member,ServiceDate) values ('G0444','3453','01-03-2017')
insert into #temp (ProcedureCode,Member,ServiceDate) values ('G0443','5676','07-03-2018')

select ProcedureCode,Member from #temp
where YEAR(ServiceDate) in (Select year(ServiceDate) ServiceDate from #temp group by 
ServiceDate having count(ServiceDate)>1)
and Member in (Select Member from #temp group by Member having count(Member)>1)
Group by ProcedureCode,Member 

 drop table #temp

enter image description here