我们说我有2张桌子
EmpID | ProcessID | ID
2 | B | 1
1 | A | 2
3 | C | 3
EmpID | ProcessID | ID
1 | F | 1
2 | E | 2
我想联合这两个表,并希望最终结果是
EmpID | ProcessID
2 | B
2 | E
1 | A
1 | F
3 | C
请注意,我的第一个表EmpID命令是2,1,3,它基于ID(标识)列。所以我想要的是UNION之后的最终结果也是2,1,3(按第一个表ID排序)。如果我使用UNION并按EmpID排序,我将改为
EmpID | ProcessID
1 | A
1 | F
2 | B
2 | E
3 | C
知道如何实现这个目标吗?
答案 0 :(得分:1)
declare @t1 table (EmpID int, ProcessID varchar(10), ID int);
insert into @t1 values
(2 ,' B' , 1),
(1 , 'A' , 2),
(3 , 'C' , 3);
declare @t2 table (EmpID int, ProcessID varchar(10), ID int);
insert into @t2 values
(1 , 'F' , 1),
(2 , 'E' , 2);
with cte2 as
(
select t2.EmpID, t2.ProcessID, t1.ID, 2 as nr
from @t1 t1 join @t2 t2
on t1.EmpID = t2.EmpID
),
cte1 as
(
select *, 1 as nr
from @t1
)
select EmpID, ProcessID
from
(
select *
from cte1
union all
select *
from cte2
)t
order by id, nr;
答案 1 :(得分:0)
如果您只需要两个第一列并删除ID列,但仍然能够按其排序,则可以这样做:
SELECT
EmpID
,ProcessID
FROM
(
SELECT
*
FROM
#tmp1 AS T
UNION
SELECT
*
FROM
#tmp2 AS T
) AS A
ORDER BY
id ASC
编辑:我注意到您的ID列在第一个表上升序排序并在辅助表上降序 - 如果总是如此,您可以这样:
SELECT
EmpID
,ProcessID
FROM
(
SELECT
EmpID
,ProcessID
,row_number() OVER (ORDER BY id asc) AS rw
FROM
#tmp1 AS T
UNION
SELECT
EmpID
,ProcessID
,row_number() OVER (ORDER BY id desc) AS rw
FROM
#tmp2 AS T
) AS A
ORDER BY
rw ASC
答案 2 :(得分:0)
试试这个脚本:
false
输出:
if (isset($_SESSION["id"])) {