我有查询,但现在我需要将查询更改为数据库,以便只为表中的每个公司获取一个结果Price
。
为此,我添加GROUP by p.id_firm
了行,然后得到下一个查询:
SELECT TOP 20
p.id_price as p_id_price,
p.id_service as p_id_service,
p.name as p_name,
p.name_original as p_name_original,
p.id_producer_country as p_id_producer_country,
p.id_firm as p_id_firm,
f.name as f_name,
f.address as f_address,
f.phone as f_phone,
city.name as city_name,
pc.name as pc_name
FROM Price p
left join Firm f
on f.id_service=p.id_service
AND f.id_city=p.id_city
AND f.id_firm=p.id_firm
left join City city
on city.id_city = p.id_city
left join Producer_country pc
on pc.id_producer_country = p.id_producer_country
WHERE p.id_city='73041'
AND p.include='1'
AND p.blocked='0'
AND f.blocked='0'
AND ( f.name LIKE 'Окно%' COLLATE SQL_Latin1_General_Cp1251_CI_AS OR p.name LIKE 'Окно%' COLLATE SQL_Latin1_General_Cp1251_CI_AS )
GROUP by p.id_firm ORDER BY p.name ASC
但是如果我使用它,我会得到错误:
消息 8120,级别 16,状态 1,第 2 行列“Price.id_price”在选择列表中无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。
请告诉我更改此查询或进行其他查询的正确方法?
结构化您可以在此处看到的所有表格
PS:抱歉不准确。按公司名称和产品名称搜索。如果搜索词包含在产品名称或公司名称中,并且有一些结果具有相同的 id_firm,则需要选择一个最合适的值,即结果搜索中的 id_firm 应该是唯一的。