简体   繁体   English

sql查询年份差异取决于特定月份

[英]sql query year difference depended on specific month

I am developing a book reservation system for a library. 我正在开发图书馆的图书预订系统。 In the table of the Reservations there are the fields: id_reservation, id_user, id_book, datetime. 在“预定”表中,有以下字段:id_reservation,id_user,id_book,datetime。

The id_user has a specific format eg: 2009897652 . id_user具有特定格式,例如: 2009897652 The first four digits indicate the year that the user was registered in the system. 前四位数字表示用户在系统中注册的年份。 All the users are registered in September (school library). 所有用户都在9月份注册(学校图书馆)。

I want to count the reservations GROUP BY the years that the user is registered. 我想计算用户注册年份的预留GROUP BY。 So I have to find the difference (integer in years) between the date of today and the September of registration year. 因此,我必须找出今天和注册年9月之间的差额(以整数为单位)。

Any help how to count the reservations GROUP BY the years that the users are registered? 对如何计算用户注册年份的预订GROUP BY有什么帮助?

eg. 例如。

total_reservations| users_registered_years
 200              | 1 
 220              | 2 
 320              | 3
 400              | 4

Thanks a lot!! 非常感谢!!

Why not just do it by the year? 为什么不按年完成呢?

select left(id_user, 4) as year, count(*)
from reservations 
group by left(id_user, 4)
order by year;

You can then just subtract the current year: 然后,您可以减去当前年份:

select year(now()) - left(id_user, 4) as diff, count(*)
from reservations 
group by left(id_user, 4)
order by diff;

I'm not sure if it worth fixing the results to make it right on any date, unless you plan on putting this query into an application. 我不确定是否值得修正结果以使其在任何日期正确,除非您计划将此查询放入应用程序中。 Then the logic is just to add an offset, like year(now()) - left(id_user, 4) + (case when month(now()) >= 10 then 1 else 0 end) . 然后,逻辑只是添加一个偏移量,例如year(now()) - left(id_user, 4) + (case when month(now()) >= 10 then 1 else 0 end)

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

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