Conditional select between dates in MySQL for maximum and minimum values of price set in a table?

MySQLMySQLi Database

You need to use CASE statement to conditional select between dates to find the minimum and maximum price. Wrap up the CASE statement with aggregate function MIN() and MAX(). The syntax is as follows:

SELECT
MIN(CASE WHEN CURDATE() BETWEEN yourStartDateColumnName AND yourEndDateColumnName THEN yourLowPriceColumnName ELSE yourHighPriceColumnName END) AS anyVariableName,

MAX(CASE WHEN CURDATE() BETWEEN yourStartDateColumnName AND yourEndDateColumnName THEN yourLowPriceColumnName ELSE yourHighPriceColumnName END) AS anyVariableName FROM yourTableName;

To understand the above syntax, let us create a table. The query to create a table is as follows:

mysql> create table ConditionalSelect
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> StartDate datetime,
   -> EndDate datetime,
   -> LowerPrice int,
   -> HigherPrice int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.69 sec)

Insert some records in the table using insert command. The query is as follows:

mysql> insert into ConditionalSelect(StartDate,EndDate,LowerPrice,HigherPrice) values('2019-01-02','2019-04-02',5,10);
Query OK, 1 row affected (0.12 sec)
mysql> insert into ConditionalSelect(StartDate,EndDate,LowerPrice,HigherPrice) values('2019-04-02','2019-04-20',0,20);
Query OK, 1 row affected (0.17 sec)
mysql> insert into ConditionalSelect(StartDate,EndDate,LowerPrice,HigherPrice) values('2019-04-03','2019-04-21',0,30);
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement. The query is as follows:

mysql> select *from ConditionalSelect;

The following is the output:

+----+---------------------+---------------------+------------+-------------+
| Id | StartDate           | EndDate             | LowerPrice | HigherPrice |
+----+---------------------+---------------------+------------+-------------+
|  1 | 2019-01-02 00:00:00 | 2019-04-02 00:00:00 |          5 |          10 |
|  2 | 2019-04-02 00:00:00 | 2019-04-20 00:00:00 |          0 |          20 |
|  3 | 2019-04-03 00:00:00 | 2019-04-21 00:00:00 |          0 |          30 |
+----+---------------------+---------------------+------------+-------------+
3 rows in set (0.00 sec)

Here is the query to select min and max price between dates:

mysql> SELECT
   -> MIN(CASE WHEN CURDATE() BETWEEN StartDate AND EndDate THEN LowerPrice ELSE HigherPrice END) AS MinimumValue,
   -> MAX(CASE WHEN CURDATE() BETWEEN StartDate AND EndDate THEN LowerPrice ELSE HigherPrice END) AS MaximumValue
   -> from ConditionalSelect;

The following is the output:

+--------------+--------------+
| MinimumValue | MaximumValue |
+--------------+--------------+
|            5 |           30 |
+--------------+--------------+
1 row in set (0.00 sec)
raja
Published on 25-Feb-2019 15:20:07
Advertisements