sql server查询顺序with union并替换多列的null值

时间:2012-09-28 09:21:42

标签: sql sql-server sql-server-2008 plsql

我有一个查询来从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.

谢谢..

3 个答案:

答案 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