我有一张如下表:
Id Price1 Price2
3 30 20
3 40 20
3 50 20
我想编写一个查询来获得以下结果:
所需的输出:
RowNo Id Price
1 3 20
2 3 30
3 3 40
4 3 50
请帮助!!
答案 0 :(得分:3)
使用Cross apply
取消数据的转出并生成行号
SELECT Row_number()OVER(ORDER BY price) AS Rowno,*
FROM (SELECT DISTINCT Id,
Price
FROM (VALUES (3,30,20),
(3,40,20),
(3,50,20) ) tc ( Id, Price1, Price2)
CROSS apply (VALUES (Price1),
(Price2)) Cs (Price)) A
结果:
╔═══════╦════╦═══════╗
║ Rowno ║ Id ║ Price ║
╠═══════╬════╬═══════╣
║ 1 ║ 3 ║ 20 ║
║ 2 ║ 3 ║ 30 ║
║ 3 ║ 3 ║ 40 ║
║ 4 ║ 3 ║ 50 ║
╚═══════╩════╩═══════╝
答案 1 :(得分:2)
您可以使用union
来组合行(因此会删除重复项)。然后row_number()
计算rownum
:
select row_number() over (order by price) as rownum, id, price
from ((select id, price1 as price from t) union
(select id, price2 from t
) t
order by price;