1

我有一个查询要从 4 个不同的表中获取记录。我union用来获取最终记录。我的问题是我在所有 4 个表中没有相同数量和类型的列,所以我正在制作具有null价值的虚拟列。我面临的问题是排序。我正在使用 datetime desc 对记录进行排序,但有时当日期相同时,我希望警报上的二级排序列可以是 High、Medium 或 Null 类型。我想要 Null 列在底部,但我在顶部。所以我尝试使用ISNULL(column_name, 'aaaa')inORDER 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.

谢谢..

4

3 回答 3

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
于 2012-09-28T09:41:56.813 回答
3

如果Alert_Type不能为 NULL in TblD,你可以这样做:

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(因为你说你想按日期时间列按降序排序)。

于 2012-09-28T10:13:48.143 回答
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
于 2012-09-28T09:25:18.753 回答