從重複的列值中獲取相應最大值的 MySQL 查詢
我們首先建立一個表 -
mysql> create table DemoTable( ProductName varchar(100), ProductPrice int ); Query OK, 0 rows affected (0.68 sec)
使用 insert 命令向表中插入一些記錄 -
mysql> insert into DemoTable values('Product-1',56);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Product-2',78);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('Product-1',88);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Product-2',86);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Product-1',45);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('Product-3',90);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Product-2',102);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values('Product-3',59);
Query OK, 1 row affected (0.13 sec)使用 select 語句從表中顯示所有記錄 -
mysql> select *from DemoTable;
這將產生以下輸出 -
+-------------+--------------+ | ProductName | ProductPrice | +-------------+--------------+ | Product-1 | 56 | | Product-2 | 78 | | Product-1 | 88 | | Product-2 | 86 | | Product-1 | 45 | | Product-3 | 90 | | Product-2 | 102 | | Product-3 | 59 | +-------------+--------------+ 8 rows in set (0.00 sec)
以下是從重複的列值中獲取相應最大值的查詢。在此,我們查詢 Product-1、Product-2 等重複列的最大 ProductPrice -
mysql> select ProductName,MAX(ProductPrice) from DemoTable group by ProductName;
這將產生以下輸出 -
+-------------+-------------------+ | ProductName | MAX(ProductPrice) | +-------------+-------------------+ | Product-1 | 88 | | Product-2 | 102 | | Product-3 | 90 | +-------------+-------------------+ 3 rows in set (0.00 sec)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP