简体   繁体   English

选择查询以通过合并两列来获得结果

[英]select query to get result by merging two columns

I have a table like below : 我有一个如下表:

Id   Price1  Price2
3     30       20
3     40       20
3     50       20

I want to write a query to get a below result : 我想写一个查询以获得以下结果:

Desired Ouput : 期望的Ouput:

RowNo  Id Price
1       3  20
2       3  30
3       3  40
4       3  50

Please help!! 请帮忙!!

Use Cross apply to unpivot the data and generate row number 使用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 

Result : 结果:

╔═══════╦════╦═══════╗
║ Rowno ║ Id ║ Price ║
╠═══════╬════╬═══════╣
║     1 ║  3 ║    20 ║
║     2 ║  3 ║    30 ║
║     3 ║  3 ║    40 ║
║     4 ║  3 ║    50 ║
╚═══════╩════╩═══════╝

You can use union to combine the rows (so duplicates are removed). 您可以使用union来合并行(因此将删除重复项)。 And then row_number() to calculate rownum : 然后使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM