有一个包含3列的表:ID,签名和日期时间,并且按“具有Count(*)> 9”的签名分组。
select * from (
select s.Signature
from #Sigs s
group by s.Signature
having count(*) > 9
) b
join #Sigs o
on o.Signature = b.Signature
order by o.Signature desc, o.DateTime
我现在想按签名选择仅第1条和第10条记录。确定排名的是Datetime降序。因此,我希望每个签名都有两行。
谢谢
答案 0 :(得分:0)
由于我不知道您的数据是什么样子,因此可能需要进行一些调整。
由于您已经知道排序顺序(DateTime DESC
)和分区(Signature
),因此这里最简单的方法可能是分配行号,然后选择所需的行。
SELECT *
FROM
(
select o.Signature
,o.DateTime
,ROW_NUMBER() OVER (PARTITION BY o.Signature ORDER BY o.DateTime DESC) [Row]
from (
select s.Signature
from #Sigs s
group by s.Signature
having count(*) > 9
) b
join #Sigs o
on o.Signature = b.Signature
order by o.Signature desc, o.DateTime
)
WHERE [Row] IN (1,10)
答案 1 :(得分:0)
我会使用几个常见的表表达式。
第一个将从表中选择所有记录以及每个签名的记录数,第二个将从第一个中选择记录数> 9并添加按签名划分的row_number-然后从其中选择row_number是1还是10:
With cte1 AS
(
SELECT ID, Signature, Datetime, COUNT(*) OVER(PARTITION BY Signature) As NumberOfRows
FROM #Sigs
), cte2 AS
(
SELECT ID, Signature, Datetime, ROW_NUMBER() OVER(PARTITION BY Signature ORDER BY DateTime DESC) As Rn
FROM cte1
WHERE NumberOfRows > 9
)
SELECT ID, Signature, Datetime
FROM cte2
WHERE Rn IN (1, 10)
ORDER BY Signature desc