MySQL query to get result by month and year based on condition?

MySQLMySQLi Database

You need to use OR condition along with WHERE clause. Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   MonthNumber int,
   YearNumber int
   );
Query OK, 0 rows affected (0.22 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(MonthNumber,YearNumber) values(11,2018);
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable(MonthNumber,YearNumber) values(3,2019);
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(MonthNumber,YearNumber) values(12,2018);
Query OK, 1 row affected (0.08 sec)

mysql> insert into DemoTable(MonthNumber,YearNumber) values(1,2019);
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(MonthNumber,YearNumber) values(12,2019);
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable(MonthNumber,YearNumber) values(6,2018);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-------------+------------+
| Id | MonthNumber | YearNumber |
+----+-------------+------------+
| 1  | 11          | 2018       |
| 2  | 3           | 2019       |
| 3  | 12          | 2018       |
| 4  | 1           | 2019       |
| 5  | 12          | 2019       |
| 6  | 6           | 2018       |
+----+-------------+------------+
6 rows in set (0.00 sec)

Following is the query to get result by month and year −

mysql> select Id,MonthNumber,YearNumber from DemoTable
where (MonthNumber >= 11 AND YearNumber = 2019)
OR
(MonthNumber <=11 AND YearNumber = 2018);

This will produce the following output −

+----+-------------+------------+
| Id | MonthNumber | YearNumber |
+----+-------------+------------+
| 1  | 11          | 2018       |
| 5  | 12          | 2019       |
| 6  | 6           | 2018       |
+----+-------------+------------+
3 rows in set (0.00 sec)
raja
Published on 20-May-2019 11:55:35
Advertisements