简体   繁体   English

Select 今年和上一年 mysql 在同一行

[英]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.我正在努力 select 2 个字段的 COUNT 分组为 this_year_total 和 last_year 作为日期的总数 - 1 年。 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所需的 output 是

date |日期 | model | model | this year (Count of id) |今年 (id 计数) | last_year (Count of id) last_year(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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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