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

标签 sql sql-server

我们有 2 张 table 预订,门票。 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);

最佳答案

按预订分组,仅接受没有其他类型的组

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

关于sql - 选择具有特定类型关联记录的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39035622/

相关文章:

sql-server - SQL Server 2005 查找数据库中特定数据类型的所有列

sql-server - SQL Server 全文搜索语法

sql-server - 使用 SSIS 压缩文件夹

sql - 更新所有表的突触中的统计信息

sql - "if, else"计算语句出现问题

sql - Informix:选择空问题

mysql - MySQL 支持 STORAGE 语法吗?

Python内部数据库使用

sql-server - 将单个列连接到逗号分隔的列表中

sql - 有没有一个重构 SQL 的工具,有点像 ReSharper for SQL