Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 如何合并不同sql的部分_Sql Server_Tsql - Fatal编程技术网

Sql server 如何合并不同sql的部分

Sql server 如何合并不同sql的部分,sql-server,tsql,Sql Server,Tsql,我有4个部分,每个部分由2个select语句组成。我需要将前两部分与第二部分合并。每个部分都包含其自己的顺序。我需要的结果出现在第一部分,其次是第二部分。仅对每个部分进行排序,而不对整个结果集进行排序 (select col1,col2,col3,col4,col5 from tableA where col1 = 'x' UNION ALL select col1,col2,col3,col4,col5 from tableB where col1 = 'x' ORDER BY Col3) -

我有4个部分,每个部分由2个select语句组成。我需要将前两部分与第二部分合并。每个部分都包含其自己的顺序。我需要的结果出现在第一部分,其次是第二部分。仅对每个部分进行排序,而不对整个结果集进行排序

(select col1,col2,col3,col4,col5 from tableA where col1 = 'x'
UNION ALL
select col1,col2,col3,col4,col5 from tableB where col1 = 'x'
ORDER BY Col3) --1st part ends here
--now I need to UNION the 2nd part
UNION ALL
(select col1,col2,col3,col4,col5 from tableA where col1 <> 'x'
UNION ALL
select col1,col2,col3,col4,col5 from tableB where col1 <> 'x'
ORDER BY Col3) --2nd part ends here

我尝试在select*FROM中包装每个选择项。。。但我对订单管理有意见。只是语法似乎不正确。

在并集之后,ORDER BY应用于整个结果集。见示例C:


在联合内的查询中不能有ORDER BY。

联合后,ORDER BY应用于整个结果集。见示例C:


您不能在联合内的查询中使用ORDER BY。

只需为此添加一列即可:

select col1,col2,col3,col4,col5, ord = 1 from tableA where col1 = 'x'
UNION ALL
select col1,col2,col3,col4,col5, ord = 1 from tableB where col1 = 'x'
UNION ALL
select col1,col2,col3,col4,col5, ord = 2 from tableA where col1 <> 'x'
UNION ALL
select col1,col2,col3,col4,col5, ord = 2 from tableB where col1 <> 'x'
ORDER BY ord, Col3

为此只需添加一列:

select col1,col2,col3,col4,col5, ord = 1 from tableA where col1 = 'x'
UNION ALL
select col1,col2,col3,col4,col5, ord = 1 from tableB where col1 = 'x'
UNION ALL
select col1,col2,col3,col4,col5, ord = 2 from tableA where col1 <> 'x'
UNION ALL
select col1,col2,col3,col4,col5, ord = 2 from tableB where col1 <> 'x'
ORDER BY ord, Col3

简单而聪明。谢谢你,巴德,简单又聪明。谢谢你,巴德。