I have a query to get records from 4 different tables. I am using union to get the final records. My problem is I don’t have same number and type of columns in all 4 tables so I am making dummy columns with null value. The problem I am facing is in sorting. I am sorting records using datetime desc, but some times when dates are same then I want the secondry sort column on alerts that can be of High, Medium or Null types. I want Null columns on bottom but I am getting on top. So I tried to use ISNULL(column_name, 'aaaa') in ORDER BY clause, but I am not getting actual result. Can any one help?
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
The error is
ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.
Thank you..
If
Alert_Typecan’t be NULL inTblD, you could do this:Note the
DESCafterCreatedDt(because you said you wanted to sort by the datetime column in descending order).