我有以下SQL
SELECT CASE
WHEN B.bookingId = P.bookingId
THEN 1
ELSE 0
END AS PAID
FROM Booking B
LEFT OUTER JOIN Payment P ON P.bookingId = B.bookingId
输出3行; 1,1和0
我想扩展此查询以输出0
值的预订详情。
我该怎么做?
由于
答案 0 :(得分:3)
select * from booking
where booking_id not in ( select bookingid from payment )
答案 1 :(得分:2)
如果您需要在付款时有一个列== 0,那么您还可以在付款时获得该列== 1.
试试这个:
select case when booking.bookingId = payment.bookingId then 1 else 0 end as paid, column_detail1, column_detail2 from booking left outter join payment on payment.bookingId = booking.bookingId
如果您只想在付费时选择信息为0,则可以尝试:
select paid_flag.paid, booking.detail1, booking.detail2 from ( select case when booking.bookingId = payment.bookingId then 1 else 0 end as paid, booking.bookingId from booking left outter join payment on payment.bookingId = booking.bookingId ) paid_flag join booking on paid_flag.bookingId = booking.bookingId where paid_flag.paid == 0
上述查询似乎可以进行优化。
答案 2 :(得分:0)
如果我理解你的问题,这将提供两者的详细信息。然后你可以忽略1个细节。
SELECT CASE
WHEN B.bookingId = P.bookingId
THEN 1
ELSE 0
END AS PAID,
B.details
FROM Booking B
LEFT OUTER JOIN Payment P ON P.bookingId = B.bookingId
其他明智的可能
SELECT CASE
WHEN B.bookingId = P.bookingId
THEN 1
ELSE 0
END AS PAID,
WHEN B.bookingId = P.bookingId
THEN ''
ELSE B.details
END AS UNPAIDDETAILS,
FROM Booking B
LEFT OUTER JOIN Payment P ON P.bookingId = B.bookingId
答案 3 :(得分:0)
如果您使用的是SQL 2005 +
;with cte as (
SELECT B.BookingId,
CASE
WHEN B.bookingId = P.bookingId
THEN 1
ELSE 0
END AS PAID
FROM Booking B
LEFT OUTER JOIN Payment P ON P.bookingId = B.bookingId
)
select B.*
from Booking B
inner join cte
on B.BookingId = cte.BookingId
where cte.PAID = 0
答案 4 :(得分:0)
因为Booking
中的行将始终存在于结果集中(因为它是JOIN中的左侧表),您只需要包含要返回列列表的列:
SELECT CASE
B.Column1Name,
B.Column2Name,
WHEN B.bookingId = P.bookingId
THEN 1
ELSE 0
END AS PAID
FROM Booking B
LEFT OUTER JOIN Payment P ON P.bookingId = B.bookingId
这将显示所有记录的预订详细信息。
如果您只对未付费记录感兴趣,请在WHERE子句中添加一些内容,将输出限制为仅限这些记录:
SELECT CASE
B.Column1Name,
B.Column2Name,
WHEN B.bookingId = P.bookingId
THEN 1
ELSE 0
END AS PAID
FROM Booking B
LEFT OUTER JOIN Payment P ON P.bookingId = B.bookingId
WHERE P.bookingID IS NOT NULL
答案 5 :(得分:0)
SELECT B.BOOKINGID AS ID, 'PAID' AS PAYMENT_STATUS
FROM BOOKING B
WHERE B.BOOKINGID IN (SELECT PAYMENT.BOOKINGID FROM PAYMENT)
UNION ALL
SELECT B.BOOKINGID, 'UNPAID'
FROM BOOKING B
WHERE B.BOOKINGID NOT IN (SELECT PAYMENT.BOOKINGID FROM PAYMENT)