0

在这个 SQL Server 查询中,我想为每个预订最多返回 1 个 lostReason。但是,子查询似乎为每个预订返回了 lostBusiness 表中的第一条记录。让我知道是否需要澄清。

SELECT        
    bookings.bookingNumber, lost.lostReason
FROM            
    bookings 
    LEFT OUTER JOIN(SELECT TOP (1) 
                       bookingNumber, 
                       lostReason
                    FROM            
                       lostBusiness) AS lost ON bookings.bookingNumber = lost.bookingNumber
4

3 回答 3

3

如果您需要多于一列

select      
    bookings.bookingNumber, lost.*
from bookings
    outer apply
    ( 
        select top 1
            lost.bookingNumber, 
            lost.lostReason,
            --other columns
        from lostBusiness as lost
        where bookings.bookingNumber = lost.bookingNumber
        order by -- put you order by here
    ) as lost

或者

;with cte as (
    select      
        *,
        row_number() over (partition by bookings.bookingNumber order by /* ??? */) as row_num
    from bookings
        left outer join lostBusiness as lost on bookings.bookingNumber = lost.bookingNumber
 )
 select * from cte where row_num = 1

如果您需要多于一列

select      
    bookings.bookingNumber, max(lost.lostReason) as lostReason
from bookings
    left outer join lostBusiness as lost on bookings.bookingNumber = lost.bookingNumber
group by bookings.bookingNumber
于 2013-08-07T13:20:59.640 回答
2

如果您只是想要任何失去的理由,MAX或者MIN会这样做:

SELECT        
    Bookings.BookingNumber, 
    MAX(LostBusiness.LostReason) as SomeLostReason
FROM            
    Bookings
    LEFT JOIN LostBusiness ON bookings.BookingNumber= lostBusiness.BookingNumber
GROUP BY
    Bookings.BookingNumber
于 2013-08-07T13:17:20.317 回答
2

您的查询失败,因为您要加入单个记录,而不是每个预订的记录。

尝试这个

select *,
    (
          select top 1 
                 lostreason 
          from lostbusiness
          where lostbusiness.bookingnumber = bookings.bookingnumber
          -- order by goes here.
      )
from bookings

您应该了解数据没有任何固有顺序,因此您应该通过order by子查询中的子句来定义“第一个”原因的含义。

于 2013-08-07T13:21:09.123 回答