简体   繁体   中英

MySQL DISTINCT before GROUP

I have a MySQL table with 10 fields. For this particular query, I only care about 4: Title, Variables, Location, Date. I would like to take the distinct values of these four groups and then group by Title, Variables. However, When I use the following query

Select DISTINCT 
       Title, 
       Variables, 
       Location, 
       Date 
  FROM ForecastsTest2 WHERE ...
GROUP BY Variables, Title 
ORDER BY Title

It groups first and then takes distinct results. Is there any way I can switch this order?

I ended up finding my solution in

SELECT Variables, 
       Title 
  FROM (SELECT DISTINCT Variables, 
                        Title, 
                        Location, 
                        Date 
       FROM MyTABLE as Table1
       ) as Table2
       WHERE ...
       GROUP BY Variables, Title
       ORDER BY TITLE

I guess I didn't do a good job of mentioning this, but I also added a HAVING COUNT(*) >= 2 in the query. In this case, the the count will happen after all non distinct rows have been removed.

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