简体   繁体   中英

Find records where year-month is between the specified year-month pairs

My data looks like this:

图片1

I want to select rows where year and month is between 11/2015 and 02/2016 . I tried the following:

SELECT * FROM traffic 
WHERE year between '2015' AND '2016'
  AND month between '11' AND '01'
  AND toll_id='14';

But the result doesn't print. The expected output looks like this . How can I solve this problem?

从(年= 2015和月> = 11)或(年= 2016和月<= 2)AND toll_id = '14'的流量中选择*

You need to escape the column names, because year and month are functions in mysql.

select *
from traffic
where toll_id = 14 and `month` between 11 and 12 and `year` = 2015 or toll_id = 14 and `month` between 1 and 2 and `year` = 2016 ;

or even better use a datetime field (assue the column is called "created_at"):

select *
from traffic
where toll_id = 14 and month(created_at) between 11 and 12 and year(created_at) = 2015 or toll_id = 14 and month(created_at) between 1 and 2 and year(created_at) = 2016;

Also take care about what's inlcuded and what's exclude when using between. The last one may be excluded.

Edit: Due to definition change in the question, I also changed the answer. Now you have two completely different conditions in where clause. You need the full condition again to check against 1 and 2 from 2016, because the or breaks your whole condition. If you don't, you would see more unexcepted results . I tested the datetime query sucessfully on my mysql database. So, the other query also works, because the condition is the same .

Here is one solution:

-- The (Y1, M1) pair must be less than or equal to (Y2, M2)

SET @Y1 = 2014;
SET @M1 = 11;
SET @Y2 = 2016;
SET @M2 = 1;

SELECT *
FROM traffic
WHERE
    toll_id = 14 
    AND @Y1 <= `year` AND `year` <= @Y2 
    AND NOT (
        (@Y1 = `year` AND `month` < @M1) OR
        (@Y2 = `year` AND `month` > @M2)
    )

It simply returns the rows where the year is within desired range minus those rows where year is same as start year but month is less than start month or year is same as end year but month is greater than end month.

SQL Fiddle

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