Filter SQL GROUP by a filter that is not in GROUP

北战南征 提交于 2021-01-29 12:39:21

问题


Im working on a stream service like app based on C# NET.Core. Im "pinging" the server from client every minute and then create a new SQL entry with time and ID of this viewer.

Here is a example of 5 minutes of view:

StreamViewerId | TrackDate
             1 | 2020-09-25 05:05:00
             1 | 2020-09-25 05:06:00
             1 | 2020-09-25 05:07:00
             1 | 2020-09-25 05:08:00
             1 | 2020-09-25 05:09:00
             1 | 2020-09-25 05:10:00
             ...

I need to make a "chart bars" based on that data and i cant make the graphic with 1 minute as xAxis, so i trying to make each graphic point at least 5 minutes or more. The problem is that if i just use below query, all the viewers are been multiplicated x5, because they ping the server every minute, so there ill be 5 rows in a group:

SELECT 
   COUNT(LiveStreamViewerId) [Count], 
   dateadd(minute,(datediff(minute,0,TrackDate)/5)*5,0) [TrackDate] 
   FROM LiveStreamViewerTracks 
   WHERE LiveStreamId = 1
GROUP BY dateadd(minute,(datediff(minute,0,TrackDate)/5)*5,0)

Im actually getting this result:

Count | TrackDate
    5 | 2020-09-25 05:05:00
    ...

And i want to consider this viewer as only one register (because is only one viewer, not 5). Below is expected result:

Count | TrackDate
    1 | 2020-09-25 05:05:00

I can't use neither SQL partition, because i cant group by viewerid because im already grouping by datetime, so i cant filter it. Someone can help?

Thanks in advance!


回答1:


Instead of COUNT(LiveStreamViewerID), you can use COUNT(DISTINCT LiveStreamViewerID) which removes duplicates.



来源:https://stackoverflow.com/questions/64060109/filter-sql-group-by-a-filter-that-is-not-in-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!