如何使用Distinct选择查询中的count元素?

时间:2013-10-01 13:44:59

标签: sql sql-server sql-server-2008

SELECT DISTINCT 
           t1.name as t1_name, 
           t1.unit as t1_unit, 
           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'

如何在其中查询t1.name

我检查代码:

SELECT DISTINCT 
           t1.name as t1_name,
           count(t1.name) as count,           
           t1.unit as t1_unit, 
           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'

但它的代码有错误:

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

我知道我写的不是count(t1.name) as count,行,而是如何得到正确的数t1.name

P.S。:查询获得具有唯一行t1.name, t1.unit, t1.id_producer_goods, t2.name的结果。计数t1.name应显示每个元素t1.name的所有计数。

1 个答案:

答案 0 :(得分:4)

你必须添加

GROUP BY t1.name,t1.unit,hi.id_producer_goods,t2.name 

每当您沿其他列使用聚合函数时,您必须为其余列添加group by子句。

对于这些你可以删除不同的。分组将为你做。