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

各予約のレコードではなく、単一のレコードに参加しているため、クエリは失敗します。

これを試して

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 に答える
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 に答える