简体   繁体   中英

Select This Year and Previous Year mysql on Same Row

I'm struggling to select the COUNT of 2 fields grouped with this_year_total and last_year as the total for date - 1 year. I've tried with no solution working so far

This is once method tried, but may highlight better what I'm trying to achieve.

SELECT `date`, `model`,
SUM(YEAR(`date`)  = YEAR(CURDATE())) as this_year,
SUM(YEAR(`date`)  = YEAR(CURDATE()) - 1) as last_year

FROM `sales`

WHERE YEAR(`date`) IN (YEAR(CURDATE()), YEAR(CURDATE()) - 1)

GROUP BY date, model DESC;

The desired output is

date | model | this year (Count of id) | last_year (Count of id)

All input appreciated:)

It seems like you want:

select
    model,
    max(date) date
    sum(date >= date_format(current_date, '%Y-01-01')) this_year,
    sum(date < date_format(current_date, '%Y-01-01')) last_year
from sales
where date >= date_format(current_date, '%Y-01-01')) - interval 1 year
group by model, date_format(date, '%m-%d')

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