SQL - 跨越不同行/ CURSOR用法的DATEDIFF分析

时间:2014-12-11 14:00:47

标签: sql-server cursor

我需要确定酒店的预订,这些预订是在5天之内完成的。

我需要查询来检查其他假日日期(对于每个supplierID),并确定彼此在5天内的日期。

我听说使用CURSOR是一种方法,可能是DATEDIFF和OVER(PARIDTION by SupplierID)的组合,但没有CURSOR功能的经验以及如何使用它。

输出应该是这样的......

enter image description here

到目前为止我的询问是......

SELECT 

    SupplierID AS 'Hotel',
    B.ID AS BookingID,
    B.Depart

    ?? AS '5 days apart'

    FROM  Bookings B
    ORDER by B.SupplierID, B.Depart

非常感谢...

2 个答案:

答案 0 :(得分:0)

您不一定需要在此处使用光标,您可以使用以下查询来执行此操作:

select b1.SupplierID sid1, b1.ID id1, b1.Depart d1,
   iif(count(*)>1,'y','n') as within5days
from Bookings b1
left join Bookings b2
on b1.SupplierID=b2.SupplierID and abs(datediff(day, b1.Depart, b2.Depart))<=5
group by b1.SupplierID, b1.ID, b1.Depart;

如果你的表现有问题,那么光标可能是更好的选择。

编辑:在on子句中添加限制以仅加入相同的供应商

答案 1 :(得分:0)

create table datestable (hotel int, booking int, holday date)
insert into datestable values
(1,111111,'20140604'),
(1,111112,'20140606'),
(1,111113,'20141012'),
(1,111114,'20141230'),
(5,211111,'20150214'),
(5,211112,'20150217'),
(5,211113,'20150328'),
(5,211114,'20150523')

SELECT *
    ,(CASE WHEN (
        SELECT TOP 1 1
        FROM datestable d2
        WHERE d1.hotel = d2.hotel AND d1.holday <> d2.holday
        AND datediff(day, d2.holday, d1.holday) BETWEEN - 5 AND 5
        ) = 1 THEN 'y' ELSE 'n' END
    ) as '5 days apart'
FROM datestable d1