我有一张桌子
declare @t table (val int)
insert INto @t (val) values (420), (420), (520), (520), (520), (620)
select
val, ROW_NUMBER() OVER (PARTITION BY val order by val) RN
from @t
返回输出:
val RN
------
420 1
420 2
520 1
520 2
520 3
620 1
期望的输出:
val RN
420 1
420 2
NULL NULL
520 1
520 2
520 3
NULL NULL
620 1
如何实现这一目标?
答案 0 :(得分:3)
这种操作应该在应用程序中完成。您可以在SQL Server中执行此操作,但它实际上更多是一个有趣的技巧,然后是推荐的答案。
我们的想法是加入您想要的行,然后使用t.n IN (2)
按顺序获取结果:
order by
我要强调,这是对select val, rn
from ((select val, ROW_NUMBER() OVER (PARTITION BY val order by val) as rn,
1 as ordering, val as val2
from @t t
) union all
(select NULL, NULL, 2, val
from @t t
group by val
)
) t
order by val2, ordering, rn;
陈述的力量的证明。真正的答案是在应用层执行此操作。
答案 1 :(得分:2)
这有效:
declare @t table (val int)
declare @n table( val int)
insert INTO @n(val) values( NULL )
insert INto @t (val)values (420),(420),(520),(520),(520),(620)
SELECT T2.val, T2.RN AS RN
FROM (
select T.val AS GRP, T.val,ROW_NUMBER()OVER(PARTITION BY T.val order by T.val)RN from @t AS T
union
select DISTINCT T.VAL AS GRP, NULL AS val, NULL AS RN FROM @t AS T
) AS T2
ORDER BY T2.GRP, ISNULL(T2.RN, 99)
要使摘要行更改主SELECT:
SELECT T2.val, T2.RN AS RN
FROM (
select T.val AS GRP, T.val,ROW_NUMBER()OVER(PARTITION BY T.val order by T.val) RN from @t AS T
union
select T.VAL AS GRP, SUM(T.VAL) AS val, NULL AS RN FROM @t AS T GROUP BY T.Val
) AS T2
ORDER BY T2.GRP, ISNULL(T2.RN, 99)
答案 2 :(得分:0)
我们都讨厌游标,但对于这个愚蠢而且希望使用小数据集的东西,你可以在sql而不是app层中强制它。但感觉很愚蠢。但你可以。
对于它的价值,这个解决方案避免了额外的"最后的NULL行。因此,它在技术上完全匹配您想要的输出。其他人到目前为止还没有。
type='number'