简体   繁体   中英

SQL Select Specific Records based on Text Value

I have a table of Countries....

CountryID     CountryCode    CountryName
1              AF             Afghanistan
2              AX             ALAND ISLANDS
3              AL             Albania
4              DZ             Algeria etc.

I am going to use this to populate a drop down menu on a web page. What I would like is to be able to have the four countries below appear first, then have the entire list appear below these four in ASC order.

CountryID    CountryCode     CountryName
236            US             United States
40             CA             Canada
76             FR             France
235            UK             United Kingdom

I have tried various approaches but not gotten it yet.

SELECT *
From [dbo].[tblCountries]
WHERE CountryID IN (236,40,76,235)
ORDER BY CountryName asc

This gives me the 4 countries I want, but does not allow me to display the another below them.

You don't need a UNION to get the result, you can use a CASE expression in an ORDER BY:

select [CountryID], [CountryCode], [CountryName]
from tblCountries
order by
  case [CountryID]
    when 236 then 1
    when 40 then 2
    when 76 then 3
    when 235 then 4
    else 5
  end, [CountryName];

See SQL Fiddle with Demo

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