简体   繁体   中英

How to group by year with the year showing only once

I have tried using the following query

select distinct Year (SaleDate) AS SaleYear,Max(SalePrice)
from Sale
group by SaleDate

The years 2010 and 2014 are showing twice,even though i used distinct and group by. the amounts in Maxprice are different as well. am i doing something wrong here?

You need to repeat year() in the group by :

select Year(SaleDate) AS SaleYear, Max(SalePrice)
from Sale
group by year(SaleDate);

SELECT DISTINCT with GROUP BY is almost never correct. All that your query does is aggregate by SaleDate and in the result set extract the year. That is why you see duplicates.

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