【问题标题】:How to modify my SQL to select values that match dates across different rows?如何修改我的 SQL 以选择与不同行中的日期匹配的值?
【发布时间】:2014-09-22 15:59:23
【问题描述】:

我有以下查询(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 为昨天(昨天有一个结帐,今天有一个签入)。

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

【问题讨论】:

  • SQL 服务器。更新了我的问题。
  • 在我看来,您需要 max(start_date)min(end_date) group by booking_type, unit_code。它不是很清楚你为什么要得到这些日期。
  • 如果您使用的是 SQL Server 2012+,则可以使用 LEAD()LAG() 分析函数。
  • 那么您希望结果看起来如何?
  • 您希望 448 的单行看起来像什么?

标签: sql sql-server tsql


【解决方案1】:

您需要加入第二个 Booking 实例:

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))

【讨论】:

  • 有人告诉我,使用您的 sql 关键字“where”附近的语法不正确。只有我把它写成了“预订”,因为它看起来像是一个错字?
  • 谢谢,好像可以了。
  • 真的很高兴我能提供帮助,哦,对了,我想一旦我们引入“Booking b1”,我们还必须为第一个 Booking 实例提供别名,这就是您的意思吗?
【解决方案2】:

如果您只想返回满足日期条件的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

【讨论】:

  • @Jason 请注意,虽然选择的答案有效,但向您的查询添加另一个联接很昂贵且没有必要。
  • 我同意这是一个更优雅/更有效的解决方案。我可能会自己调整这种方法。不过,阅读它的代码并理解其意图似乎有点困难。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-11
  • 1970-01-01
  • 2019-12-17
  • 1970-01-01
相关资源
最近更新 更多