我有這張桌子

在這里,我想按名字升序排串列格,按客戶 ID 排列來自英國的表格。我試著這樣做
select *
from tblCustomers
order by FirstName, LastName, age asc
where not country = 'uk'
但是我們不能這樣做,因為應該在表名之后使用 where 子句以及何時使用
select *
from tblCustomers
where not country = 'uk'
order by FirstName, LastName, age asc
它排除了英國,這不是我想要的解決方案。如何從客戶 ID 中按升序排列,按英國的名字和名字排序?
uj5u.com熱心網友回復:
order by使用 case 運算式構建子句,例如
declare @tblCustomers table (customer_id int, first_name varchar(12), last_name varchar(12), age int, country varchar(3));
insert into @tblCustomers (customer_id, first_name, last_name, age, country)
values
(1, 'John', 'Doe', 31, 'USA'),
(2, 'Robert', 'Luna', 22, 'USA'),
(3, 'David', 'Robinson', 22, 'UK'),
(4, 'John', 'Reinhardt', 25, 'UK'),
(5, 'Betty', 'Doe', 28, 'UAE');
select *
from @tblCustomers
order by
case when country = 'UK' then 1 else 0 end asc -- non-UK first
, case when country = 'UK' then customer_id else null end asc -- UK ordered by id
, first_name, last_name, age asc; -- Non-UK ordered as specified
回報:
| 客戶ID | 名 | 姓 | 年齡 | 國家 |
|---|---|---|---|---|
| 5 | 貝蒂 | 能源部 | 28 | 阿聯酋 |
| 1 | 約翰 | 能源部 | 31 | 美國 |
| 2 | 羅伯特 | 露娜 | 22 | 美國 |
| 3 | 大衛 | 羅賓遜 | 22 | 英國 |
| 4 | 約翰 | 萊因哈特 | 25 | 英國 |
筆記:
- 請不要使用影像,因為我們無法復制和粘貼資料
- 理想情況下提供 DDL DML(如我所示),因為這樣更容易回答
- 始終確保您的問題是一致的,并且始終使用相同的表和列名稱
- 始終提供您想要的結果
- 不要將年齡存盤在資料庫中,存盤出生日期并計算年齡。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/455289.html
下一篇:SQL創建一個新列而不是新行
