如何在sql查询中使用GROUPBY?

如何在sql查询中使用GROUPBY?,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,运行查询时,出现以下错误: 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

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

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

如何编写此查询?

错误非常清楚,可以使用带有
t2.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
中为每组
t1.name
选择哪个值?它应该选择
max
min
等。否则
按它分组

另外,删除
独特的
不需要使用
分组方式

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;
您需要按AGG函数中未使用的所有字段分组。etc MAX

试试这个

SELECT 
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 hi 
left join Table2 t2 on t1.id_web_site=t2.id_web_site 
WHERE 
t1.id='23'  
GROUP BY t1.name,t2.name

您将聚合函数用于两列,然后需要对两列进行分组

我认为您不需要在此处使用DISTINCT关键字

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 hi 
left join Table2 t2 on t1.id_web_site=t2.id_web_site 
WHERE 
t1.id='23'  
GROUP BY t1.name,t2.name

不要使用DISTINCT和GROUP BY。太多了…@jyparask,但我需要让团队变得独一无二name@TeopLome如果您想要唯一的名称,则无需使用
GroupBy
作为名称。@Key Nelson:很抱歉,我没有看到您发布了相同的答案,因为有一些微小的秒时差。呵呵,我想我们都回答了相同的时间:)也删除了DISTINCT,因为当你在该列上分组时,这不是nessecary。
           SELECT 
           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,t2.name