我需要知道在查找trip用户的住宿数据库中使用哪条SQL语句
发布于 2020-09-23 18:39:39
错误消息很清楚:group by子句需要与select一致。有些数据库足够智能,可以理解客户的名称在功能上依赖于其id,并且不需要您将名称放入group by中-但不需要将SQL Server放入。
此外,如果您希望为没有预订的客户提供0,则需要依靠来自left joined表的内容。
考虑一下:
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中,请改用方括号。
https://stackoverflow.com/questions/64025701
复制相似问题