简体   繁体   中英

How get count element in query select with Distinct?

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'

How get count t1.name in it query?

I check code:

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'

But it code have error:

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

I know that i write not aright in line count(t1.name) as count, but how get aright count t1.name ?

PS: query get results with unique rows t1.name, t1.unit, t1.id_producer_goods, t2.name . Count t1.name should show all count each element t1.name .

You have to add

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

Whenever you use an aggregate function along other columns, you have to add the group by clause for the remaining columns.

And for these you can remove the distinct. Group by will do it for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM