如何修改我的SQL以选择匹配不同行的日期的值?

时间:2014-09-22 15:59:24

标签: sql sql-server tsql

我有以下查询(SQL Server):

select a.Booking_Type, b.Unit_Code, a.Start_Date, a.End_Date
from Booking a 
inner join Property b
on a.Property_ID = b.Property_ID 
where a.Agency_ID = 1020 and
b.IsEnabled = 1 and
a.Hold_Agreement_Signed is null and 
(convert(varchar(10), a.Start_Date, 102) = convert(varchar(10), getdate(), 102) or     convert(varchar(10), a.End_Date, 102) = convert(varchar(10), getdate()-1, 102))

此查询的结果如下:

Booking_Type    Unit_Code   Start_Date             End_Date
0               448         2014-09-22 00:00:00    2014-09-28 00:00:00
0               448         2014-09-21 05:00:00    2014-09-21 05:00:00
0               K187        2014-09-19 00:00:00    2014-09-21 00:00:00
0               K187        2014-09-18 00:00:00    2014-09-21 00:00:00

我希望得到的是Unit_Code = 448的单行,因为它有一行今天的Start_Date和一行End_Date为昨天(昨天有一个结账和今天的签到)。

如何修改我的查询以获取此信息?

2 个答案:

答案 0 :(得分:1)

您需要加入第二个预订实例:

select a.Booking_Type, b.Unit_Code, a.Start_Date, a.End_Date
from Booking  inner join Property b a.Property_ID = b.Property_ID 

inner join Booking  b1
on a.Property_ID = b1.Property_ID

并将您的where条件从OR转换为AND

... convert(varchar(10), a.Start_Date, 102) = convert(varchar(10), getdate(), 102) 
**AND**   
convert(varchar(10), **B1**.End_Date, 102) = convert(varchar(10), getdate()-1, 102))

答案 1 :(得分:1)

如果您只想返回符合日期条件的Unit_Code,则应使用HAVING

select b.Unit_Code
from Booking a 
inner join Property b
   on a.Property_ID = b.Property_ID 
where a.Agency_ID = 1020 
  and b.IsEnabled = 1 
  and a.Hold_Agreement_Signed is null
GROUP BY b.Unit_Code
HAVING MAX(CASE WHEN  CAST(a.Start_Date AS DATE) = CAST(GETDATE() AS DATE) THEN 1 END) = 1
   AND MAX(CASE WHEN  CAST(a.End_Date AS DATE) = CAST(GETDATE()-1 AS DATE) THEN 1 END) = 1