gpt4 book ai didi

sql - 如何在sql查询中使用group by?

转载 作者:行者123 更新时间:2023-12-04 17:07:49 25 4
gpt4 key购买 nike

SELECT DISTINCT 
t1.name as t1_name,
MAX(t1.unit) as t1_unit,
MAX(t1.id_producer_goods) AS hi_id_producer_goods,
t2.name as t2_name
FROM Table1 t1
left join Table2 t2 on t1.id_web_site=t2.id_web_site
WHERE t1.id='23'
GROUP BY t1.name

当我运行查询时,出现以下错误:

Column 'Table2.name' is invalid in the select list because it is not contained 
in either an aggregate function or the GROUP BY clause.

如何写这个查询?

最佳答案

错误很明显,要么使用带有 t2.name 的聚合函数,要么将其添加到 GROUP BY,这取决于您要查看的期望结果对于:

SELECT 
t1.name as t1_name,
t2.name as t2_name,
MAX(t1.unit) as t1_unit,
MAX(t1.id_producer_goods) AS hi_id_producer_goods
FROM Table1 hi
left join Table2 t2 on t1.id_web_site=t2.id_web_site
WHERE t1.id='23'
GROUP BY t1.name, t2.name;

这个错误是有道理的,因为它必须知道从 t2.name 中为每组 t1.name 选择哪个值?它应该选择 maxmin 等。否则 GROUP BY 它。

此外,删除 DISTINCTGROUP BY 不需要它。

关于sql - 如何在sql查询中使用group by?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19115892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com