我需要知道在寻找旅行用户的住宿数据库中使用什么 SQL 语句
1 回答
1
错误信息很清楚:该group by子句需要与select. 一些数据库足够聪明,可以理解客户的名称在功能上取决于其 id,并且不需要您将名称放在group by- 但不是 SQL Server 中。
此外,如果您想要没有预订的客户,您需要依靠left joined 表中的内容。0
考虑:
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
我会向前迈出一步并在子查询中进行预聚合。这通常更有效:
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 Server 中,请改用方括号。
于 2020-09-23T10:39:39.453 回答