我有一些来自4个表的记录,并且date不是所有表中的通用字段,但我使用'as'。现在我需要按日期订购
select id,convert(varchar(20), SoldDate,3) as Date from sale
union
select id,convert(varchar(20), PaymentDate,3) as Date from purchase
union
select id,convert(varchar(20), PaymentClearedDate,3) as Date from payments
union
select id,convert(varchar(20), PaymentClearedDate,3) as Date from orders
order by Date desc
我需要按日期订购
答案 0 :(得分:3)
您可以使用CTE
或subquery
:
SELECT t.*
FROM ( <Query>
) t
ORDER BY r.Date DESC;
但是,我会在日期对话中争论,如果您只想约会,请使用cast(SoldDate as date)
并将后者转换为dd\MM\yy
。
因此,您更新后的查询为:
SELECT t.id, CONVERT(VARCHAR(10), t.[Date], 3) AS [Date]
FROM (SELECT id, CAST(SoldDate AS DATE) AS [Date]
FROM sale
UNION
SELECT id, CAST(PaymentDate AS DATE)
FROM purchase
UNION
. . .
) t
ORDER BY t.[Date] DESC;
答案 1 :(得分:0)
您的代码出了什么问题?据我所知,您正在按日期订购。如果您想按日期中的日期顺序进行排序,请创建另一列作为日期的日期,例如日期
select id,convert(varchar(20), SoldDate,3) as Date,SoldDate as d2 from sale
union
select id,convert(varchar(20), PaymentDate,3) as Date, PaymentDate as d2 from purchase
union
select id,convert(varchar(20), PaymentClearedDate,3) as Date, PaymentClearedDate as d2 from payments
union
select id,convert(varchar(20), PaymentClearedDate,3) as Date, PaymentClearedDate as d2 from orders
order by d2 desc
如果它们以其他某种文本格式存储,则可能需要转换日期以键入日期 例如
select id,convert(varchar(20), SoldDate,3) as Date,CAST(SoldDate as datetime2) as d2 from sale
union
...etc
order by d2 desc