TSQL DISTINCT RECORD COUNT

时间:2011-09-28 15:15:19

标签: tsql count distinct


我正在使用SSMS 2008,并试图从我的表中获取一个独特的Event_names计数。但是,当实际存在2个记录和其他无效值时,它返回count = 1。我想要的是他们所属的不同event_names数量的总计数/消费者。此外,同一消费者的一些事件计数也不同。但我想要一个不同的计数/消费者。以下是我的无效查询返回的部分数据:

消费者计划注册日期event_name Event_Ct

B, Tiffany  2010-09-27 12:00:00.000 Comprehensive Clinical Assessment   1
B, Tiffany  2010-09-27 00:00:00.000 Telemedicine Comprehensive Clinical Assessment  1
B, Nickolas Tyan    2010-12-07 15:00:00.000 Comprehensive Clinical Assessment   1
B, Nickolas Tyan    2010-12-07 00:00:00.000 Telemedicine Comprehensive Clinical Assessment  1
B, Jack 2011-06-13 08:30:00.000 Comprehensive Clinical Assessment   1
B, Jack 2011-01-03 00:00:00.000 Medication Management   1
B, Victoria Lynn    2010-11-10 00:00:00.000 Telemedicine Comprehensive Clinical Assessment  3
B, Victoria Lynn    2010-12-28 00:00:00.000 Telemedicine Psychiatric Assessment 3
B, Victoria Lynn    2011-01-07 00:00:00.000 Telemedicine Psychiatric Progress Note  2
B, Victoria Lynn    2011-02-08 00:00:00.000 Telemedicine Psychiatric Progress Note  2

这是我用于上述的T-SQL:

SELECT consumer, [Program Enrollment Date], event_name, [Program Quarter]
INTO #INITIATIONS
FROM #consumer_initiations   
WHERE consumer IN 
(SELECT DISTINCT Consumer 
FROM #consumer_initiations
GROUP BY Consumer 
HAVING Count(DISTINCT event_name) > 1)
ORDER BY consumer, event_name

SELECT A.consumer, A.[Program Enrollment Date], A.event_name, count(A.event_name)
FROM #INITIATIONS A 
JOIN #INITIATIONS B ON A.consumer = B.consumer AND A.event_name <> B.event_name AND A.[Program Enrollment Date] <> B.[Program Enrollment Date]
GROUP BY A.consumer, A.event_name, a.[Program Enrollment Date]

我也尝试过这个查询,它只为2条记录的消费者返回了正确的计数,但对于那些&gt; 2条记录,它返回的计数太高了:

SELECT A.consumer, count(A.event_name)
FROM #INITIATIONS A 
JOIN #INITIATIONS B ON A.consumer = B.consumer AND A.event_name <> B.event_name AND A.[Program Enrollment Date] <> B.[Program Enrollment Date]
GROUP BY A.consumer

感谢Chris,这里有解决方案:

Select I.consumer, [Program Enrollment Date], event_name, countPerConsumer.[Number of Events] 
From #INITIATIONS i 
Join (Select Consumer, count(distinct event_name) as [Number of Events] From #INITIATIONS GROUP BY Consumer) countPerConsumer  
    on countPerConsumer.Consumer 

= i.consumer

1 个答案:

答案 0 :(得分:1)

我想我已经掌握了你想要做的事情。如果不是我适用。这样的事情可以帮助你:

Select consumer, [Program Enrollment Date], event_name, countPerConsumer.[Number of Events]
From #INITIATIONS i
Join (Select Consumer, count(distinct event_name) as [Number of Events] 
        group by Consumer)countPerConsumer 
    on countPerConsumber.consumer = i.consumer

这个想法是你加入一个为每个消费者提供一系列不同事件的表格。你应该能够保留你构建#INITIATIONS的地方,并用上面的代码替换最后一个查询。希望这有帮助。