我需要从 SQL Server 查询中获取前 5 条记录,但要计算满足 where 子句条件的所有记录
Posted
技术标签:
【中文标题】我需要从 SQL Server 查询中获取前 5 条记录,但要计算满足 where 子句条件的所有记录【英文标题】:I need to get top 5 record from SQL Server query but count of all record which satisfy the where clause condition 【发布时间】:2020-07-02 06:04:31 【问题描述】: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
【问题讨论】:
请编辑您的问题并使用编辑框上方的
按钮。它对突出显示的文本进行操作以将其格式化为代码
(Suraj 已为您格式化代码;下次发布代码时,请在发布前格式化)
好的,我一定会做到的
@here,我的 sql 查询的第一部分基本上计算了表中满足 where 子句的所有记录,在下一部分中,我只需要获取满足相同 where 子句的前 5 条记录。跨度>
【参考方案1】:
如果您使用窗口函数进行计数,那么它会起作用:
SELECT top 5
...,
COUNT(*) OVER() as rowCount
FROM
...
WHERE
...
ORDER BY
...
如果您在窗口函数的 OVER 子句中不提供任何内容,则它指的是整个数据集
【讨论】:
谢谢你的回应,还有其他解决方案,因为我不能在这里使用窗口功能。只寻找任何有效的 sql 查询.. 窗口函数是最有效的选项。除此之外,对您的查询进行 CTE 并执行SELECT ..., (SELECT COUNT(*) FROM cte) as rowcount FROM cte WHERE ...
以上是关于我需要从 SQL Server 查询中获取前 5 条记录,但要计算满足 where 子句条件的所有记录的主要内容,如果未能解决你的问题,请参考以下文章