IntroductionIn this code snippet, I will demonstration to you all how to use the Order by clause with Union or Union all Unionselect a.* from (select top 10 ToUrl, Title+ ' (' +ltrim(rtrim(cast(HitCount as CHAR(6)))) +' views)' as Title,Description,ContentTypeIDfrom contentswhere IsActive=1 and IsPublsihed=1 and ContentTypeID=1order by HitCount desc ) as aUNIONselect b.* from (select top 10 ToUrl,Title+ ' (' +ltrim(rtrim(cast(HitCount as CHAR(6)))) +' views)' as Title,Description,ContentTypeIDfrom contentswhere IsActive=1 and IsPublsihed=1 and ContentTypeID=2order by HitCount desc) bUNIONselect c.* from (select top 10 UrlSlug as ToUrl,Title+ ' (' +ltrim(rtrim(cast(ViewCount as CHAR(6)))) +' views)' as Title,Description,ContentTypeIDfrom TipsAndTrickswhere IsActive=1 and IsPublished=1 and ContentTypeID=9order by ViewCount desc) c In above sql, you can see have I have used the sub query to order the record first, and then select from that ordered data to another table and populate data from that table. Union Allselect a.* from (select top 10 ToUrl, Title+ ' (' +ltrim(rtrim(cast(HitCount as CHAR(6)))) +' views)' as Title,Description,ContentTypeIDfrom contentswhere IsActive=1 and IsPublsihed=1 and ContentTypeID=1order by HitCount desc ) as aUNIONALLselect b.* from (select top 10 ToUrl,Title+ ' (' +ltrim(rtrim(cast(HitCount as CHAR(6)))) +' views)' as Title,Description,ContentTypeIDfrom contentswhere IsActive=1 and IsPublsihed=1 and ContentTypeID=2order by HitCount desc) bUNION ALLselect c.* from (select top 10 UrlSlug as ToUrl,Title+ ' (' +ltrim(rtrim(cast(ViewCount as CHAR(6)))) +' views)' as Title,Description,ContentTypeIDfrom TipsAndTrickswhere IsActive=1 and IsPublished=1 and ContentTypeID=9order by ViewCount desc) cI have used same idea to union all as well. hope help to you all. thank you for reading. |