简体   繁体   English

选择联合SQL

[英]Select Union SQL

I am using the following query : 我正在使用以下查询:

select 8 Union Select 0 Union Select 15 

to populate the these 3 number in a column. 将这3个数字填充到一列中。 The result I get is: 我得到的结果是:

0  
8  
15

But I want 8 to come first and then 0 and then 15, eg 但是我想先是8,然后是0,然后是15,例如

8  
0  
15

How do I do this? 我该怎么做呢?

使用UNION ALL Eg

select 8 UNION ALL Select 0 UNION ALL Select 15 

@SimonMartin's answer works for the exact data set you give, but be aware that if your data set contains duplicate values, the UNION ALL will produce different results than UNION . @SimonMartin的答案适用于您提供的确切数据集,但请注意,如果您的数据集包含重复值,则UNION ALL会产生与UNION不同的结果。

The UNION operator removes duplicates, whereas the UNION ALL will preserve them (as well as their order, as noted in @SimonMartin's answer). UNION运算符删除重复项,而UNION ALL将保留它们(以及它们的顺序,如@SimonMartin的答案所述)。

If you want to combine the functionality of your UNION operator with the ordering capabilities provided by UNION ALL , then you need to start with UNION ALL then filter out the duplicate values yourself: 如果要将UNION运算符的功能与UNION ALL提供的排序功能结合在一起,则需要从UNION ALL开始,然后自己过滤掉重复的值:

-- baseline query + 1 duplicate record at the end
with query as 
(
    select 8 as Val
        UNION ALL 
    Select 0 as Val
        UNION ALL 
    Select 15 as Val
        UNION ALL 
    Select 0 as Val
)
-- now add row numbers
, queryWithRowNumbers as 
(
    select row_number() over (order by (select 0)) as rn, Val
    from query
)
-- finally, get rid of the duplicates
select Val from (
    select Val, min(rn) as minRn
    from querywithrownumbers
    group by val
) q
order by minRn

This will give results of 这将给出结果

8
0
15

whereas if you ONLY use UNION ALL you will end up with 但是,如果仅使用UNION ALL ,则最终会得到

8
0
15
0

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

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