简体   繁体   中英

How to return a specific row to the Bottom from a SQL Query results?

I have a simple sql query which return the data as

select [BusinessModel], count(*) As Total from DimHotelExpand
group by [BusinessModel] 

The result comes as:

DA        53894
DL        7098
ECM       1472
Flex      14789
GDS       33487
Lead      1499050
MT        71306
Unknown   572467

I want the row with value 'Lead' to appear at the bottom of the result. How can I do this?

Try this one -

SELECT 
      d.BusinessModel
    , Total = COUNT(1)
FROM dbo.DimHotelExpand d
GROUP BY d.BusinessModel
ORDER BY 
      CASE WHEN d.BusinessModel = 'Lead' THEN 0 ELSE 1 END
    , Total

You can order it by your total column (since Lead's count is higher) like this:

SELECT [BusinessModel], count(*) As Total from DimHotelExpand
GROUP BY [BusinessModel]
ORDER BY count(*)

You can try this, if you don't know if Lead has always the biggest value:

select 
    [BusinessModel], count(*) As Total 
from DimHotelExpand
group by 
    [BusinessModel] 
order by 
    case [BusinessModel] when 'Lead' then 1 else 0 end asc

You can try with "union all".

select [BusinessModel], count(*) As Total from DimHotelExpand
where [BusinessModel] <> 'Lead'
group by [BusinessModel] 
union all
select [BusinessModel], count(*) As Total from DimHotelExpand
where [BusinessModel] = 'Lead'
group by [BusinessModel] 

A solution with "Order by", I believe don't work fine. Only work fine while "Lead" is more greater bussines model.

I think frikozoid solution is also valid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM