我有一张表格如下:
ID Title StartDate EndDate
1 PromoA 2012-06-01 2012-08-01
2 PromoB 2011-01-01 2011-02-01
3 PromoC 2012-09-01 2012-10-01
4 PromoD 2012-07-01 2012-09-01
因此,有4个促销状态:1-OnGoing; 2-OutOfDate; 3-Waiting; 4-OnGoing
如何按状态对其进行排序?
答案 0 :(得分:2)
DECLARE @Table TABLE
(
id int,
status varchar(20)
)
insert @table
SELECT id,
CASE WHEN (EndDate < getdate()) THEN 'OutOfDate'
WHEN (StartDate > getdate()) THEN 'Waiting'
ELSE 'Ongoing'
END AS Status
FROM Promotion
SELECT *
FROM Promotion p
inner join @Table t on t.id = p.id
ORDER BY Status
答案 1 :(得分:1)
您可以使用CASE语句对每一行进行分类,如下所示(请注意,这假定所有行都为StartDate <= EndDate
:
;WITH cte AS
(
SELECT ID, Title, StartDate, EndDate,
CASE WHEN (EndDate < CURRENT_TIMESTAMP) THEN 'OutOfDate'
WHEN (StartDate > CURRENT_TIMESTAMP) THEN 'Waiting'
ELSE 'Ongoing'
END AS [Status]
FROM Promotion
)
SELECT ID, Title, StartDate, EndDate
FROM cte
ORDER BY [Status]