SQL- UNION:如何通过 Order By 对不匹配的列进行 UNION 4 SELECT

SQL- UNION : How to UNION 4 SELECT of unmatched column by Order By

SELECT 'ABC-D Header1' As Seq1
UNION
SELECT 'ABC-D Header2' AS seq2
UNION
SELECT  ABC-D data1 data2..3..data4 ' AS seq3
UNION
SELECT 'ABC-D Tail' AS Seq4
ORDER BY SEQ1 ASC

 OUTPUT:  
 ABC-D data1 data2..3..data4
 ABC-D Header1
 ABC-D Header2     
 ABC-D Tail

EXPECTED RESULT :

ABC-D Header1
ABC-D Header2
ABC-D data1 data2..3..data4
ABC-D Tail

任何人都可以帮助我了解 UNION 在内部是如何工作的,我正在处理硬编码值,它们应该分为两行(Header1、Header2),然后是数据和尾部。 我也尝试过 ASC 和 DESC,但似乎无法给出预期的准确结果。

如有任何帮助,我们将不胜感激。

为所需的顺序添加另一列

SELECT 'ABC-D Header1' As Seq1, s = 1
UNION
SELECT 'ABC-D Header2' AS seq2, s = 2
UNION
SELECT  'ABC-D data1 data2..3..data4 ' AS seq3, s = 3
UNION
SELECT 'ABC-D Tail' AS Seq4, s = 4
ORDER BY s ASC

编辑: 如果您不希望得到 s 结果,请使用 ctederived table

; WITH CTE AS
(
    SELECT 'ABC-D Header1' As Seq1, s = 1
    UNION
    SELECT 'ABC-D Header2' AS seq2, s = 2
    UNION
    SELECT  'ABC-D data1 data2..3..data4 ' AS seq3, s = 3
    UNION
    SELECT 'ABC-D Tail' AS Seq4, s = 4
)
SELECT  Seq1
FROM    CTE
ORDER BY s ASC
select Seq1
from
(
SELECT 'ABC-D Header1' As Seq1, number = 1
UNION
SELECT 'ABC-D Header2' AS seq2, number = 2
UNION
SELECT  'ABC-D data1 data2..3..data4 ' AS seq3, number = 3
UNION
SELECT 'ABC-D Tail' AS Seq4, number = 4
) a 
ORDER BY number ASC

或者你也可以像这样使用Desired table,没有多余的列

SELECT Seq1
FROM(
 VALUES
 ('ABC-D Header1'),
 ('ABC-D Header2'),
 ('ABC-D data1 data2..3..data4 '),
 ('ABC-D Tail')
)v(Seq1)

Result here

这也是一种方法。随着 unpivot.

select seq from 
(select convert(varchar(50), 'ABC-D Header1') as seq1
        , convert(varchar(50), 'ABC-D Header2') as seq2
        , convert(varchar(50),'ABC-D data1 data2..3..data4') as seq3
        , convert(varchar(50),'ABC-D Tail') as seq4) a
unpivot (seq for seq_order in ([seq1], [seq2], [seq3], [seq4])
) as b

here is a demo

使用 convert 是因为没有它会抛出错误,即 seq3 与 UNPIVOT 列表中指定的其他列的类型冲突

结果:

您可以将 VALUES 与位置一起使用:

SELECT t.Header
FROM ( VALUES (1, 'ABC-D Header1'), 
              (2, 'ABC-D Header2'), 
              (3, 'ABC-D data1 data2..3..data4 '), 
              (4, 'ABC-D Tail'))
     ) t(Seq, Header)
ORDER BY seq;