我有一个查询来从4个不同的表中获取记录。我正在使用union
来获取最终记录。我的问题是我在所有4个表中没有相同数量和类型的列,因此我使用null
值创建虚拟列。我面临的问题是排序。我正在使用datetime desc对记录进行排序,但有时当日期相同时,我希望第二个排序列可以是High,Medium或Null类型的警报。我想要底部的Null列,但我正处于最顶层。所以我尝试在ISNULL(column_name, 'aaaa')
子句中使用ORDER BY
,但我没有得到实际的结果。任何人都可以帮忙吗?
SELECT CreatedDt as 'Date/Time' , null AS [Alert_Type] FROM TblA
union
SELECT CreatedDt as 'Date/Time' , null AS [Alert_Type] FROM TblB
union
SELECT CreatedDt as 'Date/Time' , null AS [Alert_Type] FROM TblC
union
SELECT CreatedDt as 'Date/Time' , Alert_Type FROM TblD
ORDER BY CreatedDt, ISNULL (Alert_Type,'aa') DESC
错误是
ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.
谢谢..
答案 0 :(得分:4)
试试这个:
select * from (
SELECT CreatedDt as 'Date/Time' , null AS [Alert_Type] FROM TblA
union
SELECT CreatedDt as 'Date/Time' , null AS [Alert_Type] FROM TblB
union
SELECT CreatedDt as 'Date/Time' , null AS [Alert_Type] FROM TblC
union
SELECT CreatedDt as 'Date/Time' , Alert_Type FROM TblD)a
order by CreatedDt desc,
case when Alert_Type is null then 0 else 1 end
答案 1 :(得分:3)
如果Alert_Type
中的TblD
不能为NULL,则可以执行此操作:
SELECT CreatedDt as 'Date/Time' , 'aa' AS [Alert_Type] FROM TblA
union
SELECT CreatedDt as 'Date/Time' , 'aa' AS [Alert_Type] FROM TblB
union
SELECT CreatedDt as 'Date/Time' , 'aa' AS [Alert_Type] FROM TblC
union
SELECT CreatedDt as 'Date/Time' , Alert_Type FROM TblD
ORDER BY CreatedDt DESC, Alert_Type DESC
请注意DESC
之后的CreatedDt
(因为您说您希望按日期时间列按降序排序)。
答案 2 :(得分:1)
您仍然可以在CASE
条款中使用ORDER BY
ORDER BY CASE WHEN column_name IS NULL
THEN 1
ELSE 0
END ASC --, other sorts
-- in these case NULL columns should be on the bottom part