如何在SQL Server中减去两个日期

时间:2014-03-02 06:07:40

标签: sql-server tsql

我试图找出每个订单需要多长时间才能发货。为每个订单提供ordID,客户namedays_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;

3 个答案:

答案 0 :(得分:1)

select 
OrdID,name,DATEDIFF(ShipDate,OrderDATE) as Days_to_Ship
from ORDERS, CUSTOMERS    
order by DATEDIFF(ShipDate,OrderDATE) desc;

答案 1 :(得分:0)

您尚未指定哪个RDBMS,但您可以在MySqlSqlServer中使用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;

我假设CustomersOrders之间的加入条件。

如果您只需要最长的延迟,请使用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