每个加入记录的前1名

时间:2013-08-07 13:12:27

标签: sql-server tsql greatest-n-per-group

在这个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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

如果您只是想要遗失任何理由,MAXMIN会:

SELECT        
    Bookings.BookingNumber, 
    MAX(LostBusiness.LostReason) as SomeLostReason
FROM            
    Bookings
    LEFT JOIN LostBusiness ON bookings.BookingNumber= lostBusiness.BookingNumber
GROUP BY
    Bookings.BookingNumber

答案 2 :(得分:2)

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

试试这个

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

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