我有一个问题:
SELECT
f.name as f_name,
f.address as f_address,
f.business as f_business,
f.web as f_web,
f.id_service as f_id_service,
f.id_city as f_id_city,
f.id_firm as f_id_firm,
f.phone as f_phone,
p.name as p_name
FROM Firm f
left join Price p on p.id_service=f.id_service
AND p.id_city=f.id_city AND p.id_firm=f.id_firm
WHERE
p.id_city='73041' AND
p.include='1' AND
p.blocked='0' AND
f.blocked='0'AND
p.id_group='44' AND
p.id_subgroup='369'
Group by
f.name
ORDER by
f.name ASC
我收到以下错误:
Msg 8120, Level 16, State 1, Line 4
Column 'Firm.address' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
为什么我会这样做以及如何解决?
答案 0 :(得分:2)
你应该考虑给你的问题一个更好的标题..
您无法访问select中不在GROUP BY中的列(您可能需要将它们放在MIN(...)或MAX(...)等聚合函数中)。
我不确定为什么你的查询中有GROUP BY,因为你没有进行任何聚合?
您可能希望一起删除GROUP BY。 您可能希望将所有列放在GROUP BY中。 或者您可能希望删除组,并在SQL中的SELECT之后添加DISTINCT子句(删除GROUP BY将为每行提供一个结果)。
我的猜测是你想要一个像这样的SQL:
SELECT
f.name as f_name,
f.address as f_address,
f.business as f_business,
f.web as f_web,
f.id_service as f_id_service,
f.id_city as f_id_city,
f.id_firm as f_id_firm,
f.phone as f_phone,
p.name as p_name,
SUM(p.SOMEKIND_OF_COLUMN) as sumOfPrice
FROM Firm f
left join Price p on p.id_service=f.id_service
AND p.id_city=f.id_city AND p.id_firm=f.id_firm
WHERE p.id_city='73041' AND p.include='1' AND p.blocked='0' AND f.blocked='0'
AND p.id_group='44' AND p.id_subgroup='369'
Group by
f.name,
f.address,
f.business ,
f.web,
f.id_service ,
f.id_city ,
f.id_firm ,
f.phone ,
p.name
ORDER by f.name ASC