我有一张看起来像这样的表(100亿行)
AID BID CID
1 2 1
1 6 9
0 1 4
1 3 2
1 100 2
0 4 2
0 0 1
AID只能是0或1. BID和CID可以是任何东西。 现在我想首先选择事件,AID = 1,然后AID = 0,再次AID = 1,然后AID = 0。 想法是选择相等数量的AID = 1和AID = 0事件。 我怎样才能做到这一点?
预期结果是
AID BID CID
1 2 1
0 1 4
1 6 9
0 4 2
1 3 2
0 0 1
答案 0 :(得分:3)
;WITH cte AS (
select *
FROM (VALUES
(1, 2, 1),
(1, 6, 9),
(0, 1, 4),
(1, 3, 2),
(1, 100, 2),
(0, 4, 2),
(0, 0, 1)
) as t(AID, BID, CID)
),
withrow AS (
SELECT ROW_NUMBER() OVER (PARTITION BY AID ORDER BY AID) as RN, *
FROM cte)
SELECT AID,BID,CID
FROM withrow
ORDER BY RN asc , aid desc
输出:
AID BID CID
----------- ----------- -----------
1 100 2
0 4 2
1 3 2
0 1 4
1 6 9
0 0 1
1 2 1
(7 row(s) affected)