我們可在 MySQL 中使用 SUM() 函式的計算結果 WHERE 子句嗎
我們可以在 MySQL 中使用 HAVING 子句,而不是 WHERE 子句。我們先來建立一個表 -
mysql> create table DemoTable ( Name varchar(50), Price int ); Query OK, 0 rows affected (0.79 sec)
使用 insert 命令向表中插入一些記錄 -
mysql> insert into DemoTable values('Chris',30); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('David',40); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values('Chris',10); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Mike',44); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('David',5); Query OK, 1 row affected (0.17 sec)
使用 select 語句顯示錶中的所有記錄 -
mysql> select *from DemoTable;
這會生成以下輸出 -
+-------+-------+ | Name | Price | +-------+-------+ | Chris | 30 | | David | 40 | | Chris | 10 | | Mike | 44 | | David | 5 | +-------+-------+ 5 rows in set (0.00 sec)
以下是在 HAVING 子句中使用 SUM() 函式計算結果的查詢 -
mysql> select Name,SUM(Price) AS Total_Price from DemoTable group by Name having Total_Price > 40;
這會生成以下輸出 -
+-------+-------------+ | Name | Total_Price | +-------+-------------+ | David | 45 | | Mike | 44 | +-------+-------------+ 2 rows in set (0.03 sec)
廣告