Toleo
Toleo

Reputation: 774

Select record by month between 12 and 2 of new Year

I have this record:

[id | dateofit ]
[ 1 | 2017-12-1]

Which I want to select using this Query:

SELECT id FROM records WHERE MONTH(dateofit) BETWEEN 12 AND 2

The problem is that 12 is from year 2017 and 2 from year 2018, So I don't get any results,

I tried to replace the Query like this MONTH(dateofit) BETWEEN MONTH(12) AND MONTH(1) But still the same problem

What I want to do is to select records has a month of [12, 1(newyear), 2(newyear)]

Upvotes: 0

Views: 35

Answers (3)

stackFan
stackFan

Reputation: 1608

Why not provide just the time-range?

SELECT id FROM records WHERE dateofit BETWEEN "2017-12-01 00:00:00" AND "2018-03-01 23:59:59";

Upvotes: 2

tysonwright
tysonwright

Reputation: 1525

Here's two possible approaches: If you only have data from March 2017 to November 2018:

SELECT
    id
FROM
    records
WHERE
    MONTH(dateofit) IN (12, 1, 2)

If you have mulitple years of data:

SELECT
    id
FROM
    records
WHERE
    dateofit BETWEEN '2017-12-01' AND '2018-02-28'

Upvotes: 1

kc2018
kc2018

Reputation: 1460

Try this:

SELECT id FROM records 
WHERE ( YEAR(dateofit) = 2017 AND MONTH(dateofit) = 12) OR 
      ( YEAR(dateofit) = 2018 AND MONTH(dateofit) IN (1, 2));

Upvotes: 0

Related Questions