构造返回顺序的单选语句取决于 SQL Server 中列的值


Table1
Id bigint primary key identity(1,1)
Status nvarchar(20)

插入虚拟数据

Insert into Table1 values ('Open') --1
Insert into Table1 values ('Open') --2
Insert into Table1 values ('Grabbed') --3
Insert into Table1 values ('Closed') --4
Insert into Table1 values ('Closed') --5
Insert into Table1 values ('Open') --6

我将如何构造一个单一的选择语句,该语句对具有'Grabbed'状态的记录首先是数据进行排序,然后是'Closed',然后是 SQL Server 中的'Open'

输出:

Id    Status
3     Grabbed
4     Closed
5     Closed
1     Open
2     Open
6     Open

我认为你需要这样的东西:

select *
from yourTable
order by case when Status = 'Grabbed' then 1
when Status = 'Closed' then 2
when Status = 'Open' then 3
else 4 end
, Id;

[SQL Fiddle Demo]


另一种方法是像这样使用 CTE:

;with cte as (
select 'Grabbed' [Status], 1 [order]
union all select 'Closed', 2
union all select 'Open', 3
)
select t.*
from yourTable t
left join cte 
on t.[Status] = cte.[Status]
order by cte.[order], Id;

[SQL Fiddle Demo]

通过适当的规范化设计可以更好地完成此操作:

不要将Status存储为文本内容。想象一下错别字(一行Grabed(...

此外,查找表允许您添加侧面数据,例如排序顺序。

CREATE TABLE StatusLookUp(StatusID INT IDENTITY PRIMARY KEY /*you should name your constraints!*/
,StatusName VARCHAR(100) NOT NULL
,SortRank INT NOT NULL)
INSERT INTO StatusLookUp VALUES
('Open',99) --ID=1
,('Closed',50)--ID=2
,('Grabbed',10)--ID=3
CREATE TABLE Table1(Id bigint primary key identity(1,1) /*you should name your constraints!*/
,StatusID INT FOREIGN KEY REFERENCES StatusLookUp(StatusID));
Insert into Table1 values (1) --1
Insert into Table1 values (1) --2
Insert into Table1 values (3) --3
Insert into Table1 values (2) --4
Insert into Table1 values (2) --5
Insert into Table1 values (1) --6
SELECT *
FROM Table1 AS t1
INNER JOIN StatusLookUp AS s ON t1.StatusID=s.StatusID
ORDER BY s.SortRank;

我发现最简单的方法使用字符串:

order by charindex(status, 'Grabbed,Closed,Open')

或:

order by charindex(',' + status + ',', ',Grabbed,Closed,Open,')

如果要在查询中输入值,我认为最简单的方法是使用values()

select t1.*
from t1 left join
(values ('Grabbed', 1), ('Closed', 2), ('Open', 3)) v(status, priority)
on t1.status = v.status
order by coalesce(v.priority, 4);

最后。 这种需求表明您应该有一个状态的参考表。 不要将字符串名称放在其他表中,而是输入 id。 引用表可以具有优先级以及其他信息。

试试这个:

select Id,status from tablename where status='Grabbed'
union
select Id,status from tablename where status='Closed'
union
select Id,status from tablename where status='Open'

相关内容

最新更新