在 MySQL 中,在表中设置的价格最大值和最小值之间按日期条件选择?
您需要使用 CASE 语句在日期之间有条件地进行选择,以找到最低和最高价格。使用聚合函数 MIN() 和 MAX() 包装 CASE 语句。语法如下所示
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;
为了理解上述语法,让我们创建一个表。创建表的查询如下所示
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 命令向表中插入一些记录。查询如下所示
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)
使用 select 语句从表中显示所有记录。查询如下所示
mysql> select *from ConditionalSelect;
以下是输出
+----+---------------------+---------------------+------------+-------------+ | 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)
以下是查询在日期之间的最小和最大价格
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;
以下是输出
+--------------+--------------+ | MinimumValue | MaximumValue | +--------------+--------------+ | 5 | 30 | +--------------+--------------+ 1 row in set (0.00 sec)
广告