DateDiff的2个日期在同一列SQL中

时间:2014-04-29 13:45:33

标签: sql sql-server sql-server-2005

使用SQL Server 2005我需要获取同一列中2个日期的datediff,表格如下:

OrderNo    OpNo    ResType    LoadedStartDate
-----------------------------------------------------
12345      1       PAINT      2014-05-01 00:00:00.000
12345      2       PAINT      2014-05-02 00:00:00.000
12345      3       PAINT      2014-05-03 00:00:00.000
12345      4       ASMB       2014-05-04 00:00:00.000
67890      1       PAINT      2014-05-02 00:00:00.000
67890      2       PAINT      2014-05-03 00:00:00.000
67890      3       PAINT      2014-05-04 00:00:00.000
67890      4       ASMB       2014-05-05 00:00:00.000

我需要获得OpNo 1和OpNo 4的日期差异,它们是相同的订单号。 OpNo将始终为1和4,就像我要比较的那样,ResType也是如此。

输出需要如下所示:

OrderNo    Difference
----------------------
12345      3
67890      3

感谢您的帮助:)

4 个答案:

答案 0 :(得分:4)

只需将表格加入自身:

SELECT t1.OrderNo,DATEDIFF(day,t1.LoadedStartDate,t2.LoadedStartDate)
FROM UnnamedTableFromQuestion t1
       INNER JOIN
     UnnamedTableFromQuestion t2
       on
         t1.OrderNo = t2.OrderNo
WHERE t1.OpNo = 1 and
      t2.OpNo = 4

答案 1 :(得分:0)

应该非常简单

SELECT DATEDIFF(day, 
         (SELECT LoadedStartDate FROM Orders WHERE OrderNo = 12345 AND OpNo = 1),
         (SELECT LoadedStartDate FROM Orders WHERE OrderNo = 12345 AND OpNo = 4)
       )

由于内部选择返回标量值 - 它们可以用作DATEDIFF函数的参数

要使表格适用于表格中的所有订单,您可以执行以下操作:

SELECT DISTINCT OrderNo, DATEDIFF(day, 
          (SELECT LoadedStartDate FROM Orders WHERE OrderNo = Ord.OrderNo AND OpNo = 1),
          (SELECT LoadedStartDate FROM Orders WHERE OrderNo = Ord.OrderNo AND OpNo = 4)
       ) AS Diff
FROM Orders Ord

演示:http://sqlfiddle.com/#!3/bc085/5

答案 2 :(得分:0)

CTE在这种情况下工作很奇怪。根据您的要求,您可以使用以下查询。

with op1
As
(
select orderno, opno, restype, LoadedStartDate From orders
where opno = 1
),
op4
As
(
select orderno, opno, restype, LoadedStartDate From orders
where opno = 4
)
select op1.orderno, datediff(day, op1.loadedstartdate, op4.loadedstartdate) DifferenceDays 
from op1 inner join op4 on op1.orderno = op4.orderno

希望有所帮助

答案 3 :(得分:0)

SELECT DISTINCT ORDERNO,MAX(DATEPART(DAY,LoadedStartDate))-MIN(DATEPART(DAY,LoadedStartDate))
FROM ORDERS GROUP BY ORDERNO

请注意,您可以使用:

SELECT DISTINCT ORDERNO,MAX(LoadedStartDate)-MIN(LoadedStartDate) FROM ORDERS GROUP BY ORDERNO

以日期时间格式返回4天;也许是因为没有时间,并且由于MIN和MAX的性质,数据库假定从第一天开始到第四天结束整整四天。

如果你确实有订单时间并且你想要在第一个和最后一个订单之间有一个确切的时间跨度,那么可以将两个日期时间转换为一个整数,它以毫秒为单位给出每个数字,从较高的数字中减去较低的数字,然后将答案重新翻译成日期时间格式。