Rajesh
Rajesh

Reputation: 129

I need to get top 5 record from SQL Server query but count of all record which satisfy the where clause condition

select count(1) 
from chatmessage 
where ChatThreadId in ('A84B95F5-10E7-483C-A4C7-73EF4CBF48EC',
                       '85DAFD40-697C-486C-BB3B-86357CFF6A36',
                       '85DAFD40-697C-486C-BB3B-86357CFF6A36',
                       '7EA0C528-F43C-4DAF-9DFC-068E15177033',
                       'D2B15F10-7F6B-421C-8DA0-F8299BD5FFC5',
                       '85DAFD40-697C-486C-BB3B-86357CFF6A36',
                       '7EA0C528-F43C-4DAF-9DFC-068E15177033',
                       '85DAFD40-697C-486C-BB3B-86357CFF6A36',
                       'A852D60D-480A-45E9-B1AF-D51736BC7CBB',
                       'A84B95F5-10E7-483C-A4C7-73EF4CBF48EC',
                       'A852D60D-480A-45E9-B1AF-D51736BC7CBB',
                       'D2B15F10-7F6B-421C-8DA0-F8299BD5FFC5' )
  and MessageType = 1 
  and TenantId = '1B948F4A-67D7-4A50-A458-0CA16DAB4FAD' 
  and Createddate between '2014-06-24 06:43:40.5374427' and '2016-06-24 06:43:40.5374427' 
  and ModifiedDate between '2014-06-24 13:29:03.6922719' and '2016-06-24 13:29:03.6922719'

select top 5     
    ChatMessageId, ChatThreadId, MessageType, Message,
    TenantId, CreatedBy, Createddate, ModifiedDate 
from 
    chatmessage 
where 
    ChatThreadId in ('A84B95F5-10E7-483C-A4C7-73EF4CBF48EC',
                     '85DAFD40-697C-486C-BB3B-86357CFF6A36',
                     '85DAFD40-697C-486C-BB3B-86357CFF6A36',
                     '7EA0C528-F43C-4DAF-9DFC-068E15177033',
                     'D2B15F10-7F6B-42 1C-8DA0-F8299BD5FFC5',
                     '85DAFD40-697C-486C-BB3B-86357CFF6A36',
                     '7EA0C528-F43C-4DAF-9DFC-068E15177033',
                     '85DAFD40-697C-486C-BB3B-86357CFF6A36',
                     'A852D60D-480A-45E9-B1AF-D51736BC7CBB',
                     'A84B95F5-10E7-483C-A4C7-73EF4CBF48EC',
                     'A852D60D-480A-45E9-B1AF-D51736BC7CBB',
                     'D2B15F10-7F6B-421C-8DA0-F8299BD5FFC5' )
  and MessageType = 1 
  and TenantId = '1B948F4A-67D7-4A50-A458-0CA16DAB4FAD' 
  and Createddate between '2014-06-24 06:43:40.5374427' and '2016-06-24 06:43:40.5374427' 
  and ModifiedDate between '2014-06-24 13:29:03.6922719' and '2016-06-24 13:29:03.6922719'
order by  
    CreatedDate desc

Upvotes: 0

Views: 167

Answers (1)

Caius Jard
Caius Jard

Reputation: 74660

If you do your counting with a window function then it will work out:

SELECT top 5
   ...,
   COUNT(*) OVER() as rowCount
FROM
   ...
WHERE
   ...
ORDER BY
   ...

If you don't provide anything in the OVER clause of a window function it refers to the whole dataset

Upvotes: 2

Related Questions