选择具有特定类型的关联记录的记录

时间:2016-08-19 09:29:11

标签: sql sql-server

我们有2张桌子预订,门票。 Ticket.BookingId是Booking.Id的外键: enter image description here

如何为具有类型为1或3或7的票证的选择预订编写SQL select(与MS SQL Server兼容)?

东西:

select Booking.Id
from Booking 
    join Ticket on Ticket.BookingId = Booking.Id
group by Booking.Id
having Ticket.Type IN (1,3,7)

例如,在这种情况下:

enter image description here

最终结果将:2,3。

Booking.Id = 1不是最终结果,因为在表中Ticket是票证(Id = 4,BookingId = 1,Type = 8),所以此预订还包含除1或3或7之外的其他票证

LINQ中的解决方案:

var result = (from b in Booking 
join t in Ticket on Booing.Id equals Ticket.BooingId
group new {b,t} by b.Id).Where(group => group.Where(itemOfGroup=>itemOfGroup.Ticket.Type != 1 && itemOfGroup.Ticket.Type != 3 && itemOfGroup.Ticket.Type != 7).Count() == 0 ).Select(group => group.Key);

1 个答案:

答案 0 :(得分:3)

按预订分组,只拍摄那些没有其他类型的团体

select Booking.Id
from Booking 
join Ticket on Ticket.BookingId = Booking.Id
group by Booking.Id 
having sum(case when Ticket.Type NOT IN (1,3,7) then 1 else 0 end) = 0