我需要从SQL Server查询中获取前5条记录,但所有满足where子句条件的记录的计数

问题描述 投票:0回答:1
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
sql-server sql-server-2005 sql-server-2012 ssms
1个回答
1
投票
如果您使用窗口函数进行计数,那么它将起作用:

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

© www.soinside.com 2019 - 2024. All rights reserved.