我试图找出每个订单需要多长时间才能发货。为每个订单提供ordID
,客户name
和days_to_ship
。将它们从最长的延迟(在订单日期和发货日期之间)列出到最短的时间。
SELECT OrdID, name, (ShipDate-orderDate) AS Days_to_Ship
FROM ORDERS, CUSTOMERS
WHERE ShipDate-OrderDate=(select Max(ShipDate-OrderDate) from orders)
ORDER BY Days_to_Ship DESC;
答案 0 :(得分:1)
select
OrdID,name,DATEDIFF(ShipDate,OrderDATE) as Days_to_Ship
from ORDERS, CUSTOMERS
order by DATEDIFF(ShipDate,OrderDATE) desc;
答案 1 :(得分:0)
您尚未指定哪个RDBMS,但您可以在MySql和SqlServer中使用DATEDIFF
(略有不同的实现)。 MySql的DateDiff
以天为单位返回差异:
select o.OrdID, c.Name, DATEDIFF(o.ShipDate, o.OrderDate) as Days_to_Ship
from ORDERS o
INNER JOIN CUSTOMERS c on o.CustomerId = c.CustomerId
order by Days_to_Ship desc;
对于Sql Server,您需要指定DateDiff
的时间间隔,并切换日期:
select o.OrdID, c.Name, DATEDIFF(dd, o.OrderDate, o.ShipDate) as Days_to_Ship
from ORDERS o
INNER JOIN CUSTOMERS c on o.CustomerId = c.CustomerId
order by Days_to_Ship desc;
我假设Customers
和Orders
之间的加入条件。
如果您只需要最长的延迟,请使用LIMIT 1
(MySql)或TOP 1
(Sql Server)限制列表 - 与Order By
一起使用,您无需评估完全WHERE MAX
。
答案 2 :(得分:0)
您可以使用DATEDIFF
DATEDIFF(dd, dateTimeField1, dateTimeField2)
其中dd
用于区分天数。你也可以使用别人。
像
datepart Abbreviation year yy, yyyy quarter qq, q month mm, m dayofyear dy, y day dd, d week wk, ww weekday dw, w hour hh minute mi, n second ss, s millisecond ms microsecond mcs nanosecond ns