SQL 查询以确定预订的住宿

SQL Query to identify accommodation booked

我需要知道在寻找旅行用户的住宿数据库中使用什么SQL语句

错误信息很清楚:group by子句需要与select保持一致。一些数据库足够聪明,可以理解客户的姓名在功能上取决于其 ID,并且不需要您将姓名放在 group by - 但不是 SQL 服务器中。

此外,如果您想要 0 没有预订的客户,您需要依靠来自 left joined table 的东西。

考虑:

select c.customer_id, c.customer_name, count(ab.customer_id) as [number of accomm slots]
from customers c
left join  accommodation_bookings ab on c.customer_id = ab.customer_id
group by c.customer_id, c.customer_name

我会向前迈出一步,pre-aggregate 在子查询中。这通常更有效:

select c.customer_id, c.customer_name, coalesce(ab.cnt, 0) [number of accomm slots]
from customers c
left join (
    select customer_id, count(*) cnt
    from accommodation_bookings 
    group by customer_id
) ab on c.customer_id = ab.customer_id

您也可以使用相关子查询或横向连接来表达这一点:

select c.customer_id, c.customer_name, ab.*
from customers c
outer apply (
    select count(*) [number of accomm slots]
    from accommodation_bookings ab
    where c.customer_id = ab.customer_id
) ab

这将利用 accommodation_bookings(customer_id) 上的索引(如果您设置了外键,该索引应该已经存在)。

注意:不要对标识符使用单引号 - 它们用于文字字符串。在 SQL 服务器中,请改用方括号。