我SELECT
在SQL Server中有问题。我需要选择一个表的前3条记录,然后需要在这3行中查找有条件的记录。我写了这个,但是结果不正确。
SELECT TOP (3) *
from data
where state='c'
order by time desc
我的表(数据)是这样的:
code data state time
A1 12 n 2020/05/08 12:00
A2 13 c 2020/05/08 11:59
A3 10 n 2020/05/08 11:58
A4 7 c 2020/05/08 11:57
A5 18 e 2020/05/08 11:56
A6 14 c 2020/05/08 11:55
我需要这样的结果:
A2 13 c 2020/05/08 11:59
但我的查询结果是:
A2 13 c 2020/05/08 11:59
A4 7 c 2020/05/08 11:57
A6 14 c 2020/05/08 11:55
意味着我需要在前3行中按state ='c'查找记录,而不是包含state ='c'的表的前3条记录
希望我的解释清楚。我该怎么办?
一种方法是对前三行使用CTE(公用表表达式),然后对过滤条件进行外部查询:
WITH top3 AS (
SELECT TOP (3) *
FROM data
ORDER BY time DESC
)
SELECT *
FROM top3
WHERE state='c';
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句