如何在sql查询中使用group?

时间:2013-10-01 12:14:56

标签: 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=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.

如何撰写此查询?

4 个答案:

答案 0 :(得分:5)

错误很明显,要么使用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

另外,DISTINCT删除GROUP BY不需要{。}}。

答案 1 :(得分:1)

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

您需要按AGG功能中未使用的所有字段进行分组。等MAX

答案 2 :(得分:0)

试试这个

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

您正在使用具有2列的聚合函数,然后您需要在两列上进行分组

答案 3 :(得分:0)

我认为这里不需要DISTINCT关键字。

           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