我有如下表格数据。
d1 date sale_time
N 2012-03-09 00:00:00.000 TBD
No 2011-09-26 00:00:00.000 2:00 PM CT
N 2012-01-26 00:00:00.000 1:00 PM CT
N 2012-03-07 00:00:00.000 1:00 PM ET
yes 2012-02-23 00:00:00.000 Accepting Offers
我希望按日期asc,销售时间asc的结果顺序(如果销售时间不包含它应该到最后记录的时间) 我想要像
一样 d1 date sale_time
No 2011-09-26 00:00:00.000 2:00 PM CT
N 2012-01-26 00:00:00.000 1:00 PM CT
N 2012-03-07 00:00:00.000 1:00 PM ET
YEs 2012-02-23 00:00:00.000 Accepting Offers
N 2012-03-09 00:00:00.000 TBD
我尝试使用以下查询但在转换销售时间时遇到错误。
select
*
from
table
order by
date asc,
convert(datetime, SUBSTRING(replace(sale_time,' ',''),
1,
(CHARINDEX(':',replace(sale_time,' ',''))+4))) asc
答案 0 :(得分:0)
也许这会有所帮助:
首先是一些测试数据:
DECLARE @tbl TABLE(d1 VARCHAR(100),[date] DATETIME,sale_time VARCHAR(100))
INSERT INTO @tbl
VALUES
('N','2012-03-09 00:00:00.000','TBD'),
('No','2011-09-26 00:00:00.000','2:00 PM CT'),
('N','2012-01-26 00:00:00.000','1:00 PM CT'),
('N','2012-03-07 00:00:00.000','1:00 PM ET'),
('yes','2012-02-23 00:00:00.000','Accepting Offers')
然后查询:
;WITH CTE AS
(
SELECT
(
CASE
WHEN NOT CHARINDEX(':',sale_time)=0
THEN SUBSTRING(sale_time,0,5)
ELSE NULL
END
) AS sale_time_format,
tbl.d1,
tbl.date,
tbl.sale_time
FROM
@tbl AS tbl
)
SELECT
CTE.d1,
CTE.date,
CTE.sale_time
FROM
CTE
ORDER BY
CTE.sale_time_format DESC,
CTE.date
你也不需要按日期订购。只需使用sale_time_format即可获得所需的结果。我已将其包含在内,因为您可能拥有更多数据。