我正在使用SQL 2008.(实际上是在asp中)。
SELECT orderId, CONVERT(varchar, orderDate, 101) AS Date_Ordered, CONVERT(varchar, sentDate, 101) AS Date_Shipped,
FROM orders
GROUP BY orderId, CONVERT(varchar, o.orderDate, 101), CONVERT(varchar, o.sentDate, 101)
ORDER BY Date_Shipped
好的,我在Select中使用Convert的原因是因为我的Data有不同时间的日期。但我希望所有结果都在同一天。所以我使用了转换。
我的问题是我无法弄清楚如何执行Order By。 我尝试按Date_Shipped排序,但它现在是一个String,所以它没有正确排序。
有人可以帮忙吗?
答案 0 :(得分:1)
您拥有SQL Server 2008,因此您可以使用日期类型
SELECT
orderId,
CONVERT(varchar, orderDate, 101) AS Date_Ordered,
CONVERT(varchar, CAST(sentDate as date), 101) AS Date_Shipped
FROM orders
GROUP BY
orderId, CONVERT(varchar, o.orderDate, 101), CAST(sentDate as date)
ORDER BY
CAST(sentDate as date)
我不记得确切是否允许这样做但希望你明白:如果没有,请使用此
SELECT
orderId,
Date_Ordered,
CONVERT(varchar, sentDate2, 101) AS Date_Shipped
FROM
(
SELECT
orderId,
CONVERT(varchar, orderDate, 101) AS Date_Ordered,
CAST(sentDate as date) AS sentDate2
FROM orders o
GROUP BY
orderId, CONVERT(varchar, orderDate, 101), CAST(sentDate as date)
) foo
ORDER BY
sentDate2
答案 1 :(得分:0)
SELECT
orderId,
CONVERT(varchar, orderDate, 101) AS Date_Ordered,
CONVERT(varchar, sentDate, 101) AS Date_Shipped,
FROM orders
GROUP BY
orderId,
CONVERT(varchar, orderDate, 101),
CONVERT(varchar, sentDate, 101)
ORDER BY MAX(sentDate)
顺便说一下,查询中的o
别名是错误的,因为你没有像这样的别名表。