gpt4 book ai didi

SQL - 如何在 UNION 查询中排序

转载 作者:行者123 更新时间:2023-12-05 08:42:36 24 4
gpt4 key购买 nike

有没有办法联合两个表,但保持第一个表中的行首先出现在结果集中?但是 orderby 列不在选择查询中

例如:

表一

name        surname
-------------------
John Doe
Bob Marley
Ras Tafari

表2

name       surname
------------------
Lucky Dube
Abby Arnold
Result

预期结果:

name        surname
-------------------
John Doe
Bob Marley
Ras Tafari
Lucky Dube
Abby Arnold

我通过以下查询带来数据

SELECT name,surname FROM TABLE 1 ORDER BY ID  
UNION
SELECT name,surname FROM TABLE 2

上面的查询并没有跟踪 after union 的顺序。
P.S - 我不想在我的选择查询中显示 ID
我通过连接表获得 ORDER BY Column。以下是我的真实查询

  SELECT tbl_Event_Type_Sort_Orders.Appraisal_Event_Type_ID AS Appraisal_Event_Type_ID , ISNULL(tbl_Appraisal_Event_Types.Appraisal_Event_Type_Display_Name, 'UnCategorized') AS  Appraisal_Event_Type_Display_Name 
INTO #temptbl
FROM tbl_Event_Type_Sort_Orders
INNER JOIN tbl_Appraisal_Event_Types
ON tbl_Event_Type_Sort_Orders.Appraisal_Event_Type_ID = tbl_Appraisal_Event_Types.Appraisal_Event_Type_ID
WHERE 1=1
AND User_Name='abc'
ORDER BY tbl_Event_Type_Sort_Orders.Sort_Order

SELECT * FROM #temptbl
UNION
SELECT DISTINCT (tbl_Appraisal_Event_Types.Appraisal_Event_Type_ID) AS Appraisal_Event_Type_ID , ISNULL(tbl_Appraisal_Event_Types.Appraisal_Event_Type_Display_Name, 'UnCategorized') AS Appraisal_Event_Type_Display_Name
FROM tbl_Appraisal_Event_Types
INNER JOIN tbl_Appraisal_Events
ON tbl_Appraisal_Event_Types.Appraisal_Event_Type_ID = tbl_Appraisal_Events.Event_Type_ID
INNER JOIN tbl_Appraisals
ON tbl_Appraisal_Events.Appraisal_ID = tbl_Appraisal_Events.Appraisal_ID
WHERE 1=1
AND ((tbl_Appraisals.Assigned_To_Staff_User) = 'abc' OR (tbl_Appraisals.Assigned_To_Staff_User2) = 'abc' OR (tbl_Appraisals.Assigned_To_Staff_User3) = 'abc')

最佳答案

UNION ALL 放入派生表中。要保持重复消除,请执行 select distinct 并向第二个 select 添加 NOT EXISTS 以避免在两个表中找到同一个人两次:

select name, surname
from
(
select distinct name, surname, 1 as tno
from table1
union all
select distinct name, surname, 2 as tno
from table2 t2
where not exists (select * from table1 t1
where t2.name = t1.name
and t2.surname = t1.surname)
) dt
order by tno, surname, name

关于SQL - 如何在 UNION 查询中排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39592982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com