新聞中心
SQL HAVING 子句
HAVING 子句
在 SQL 中增加 HAVING 子句原因是,WHERE 關(guān)鍵字無(wú)法與聚合函數(shù)一起使用。

創(chuàng)新互聯(lián)主營(yíng)鹽亭網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,app軟件開發(fā)公司,鹽亭h5小程序開發(fā)搭建,鹽亭網(wǎng)站營(yíng)銷推廣歡迎鹽亭等地區(qū)企業(yè)咨詢
HAVING 子句可以讓我們篩選分組后的各組數(shù)據(jù)。
SQL HAVING 語(yǔ)法
SQL HAVING 語(yǔ)法
SELECT
column1
,
aggregate_function
(
column2
)
FROM
table_name
GROUP
BY
column1
HAVING
condition
;
參數(shù)說(shuō)明:
column1:要檢索的列。aggregate_function(column2):一個(gè)聚合函數(shù),例如SUM、COUNT、AVG等,應(yīng)用于column2的值。table_name:要從中檢索數(shù)據(jù)的表。GROUP BY column1:根據(jù)column1列的值對(duì)數(shù)據(jù)進(jìn)行分組。HAVING condition:一個(gè)條件,用于篩選分組的結(jié)果。只有滿足條件的分組會(huì)包含在結(jié)果集中。
演示數(shù)據(jù)庫(kù)
在本教程中,我們將使用 RUNOOB 樣本數(shù)據(jù)庫(kù)。
下面是選自 "Websites" 表的數(shù)據(jù):
+----+--------------+---------------------------+-------+---------+ | id | name | url | alexa | country | +----+--------------+---------------------------+-------+---------+ | 1 | Google | https://www.google.cm/ | 1 | USA | | 2 | 淘寶 | https://www.taobao.com/ | 13 | CN | | 3 | 菜鳥教程 | http://www.runoob.com/ | 4689 | CN | | 4 | 微博 | http://weibo.com/ | 20 | CN | | 5 | Facebook | https://www.facebook.com/ | 3 | USA | | 7 | stackoverflow | http://stackoverflow.com/ | 0 | IND | +----+---------------+---------------------------+-------+---------+
下面是 "access_log" 網(wǎng)站訪問記錄表的數(shù)據(jù):
mysql> SELECT * FROM access_log; +-----+---------+-------+------------+ | aid | site_id | count | date | +-----+---------+-------+------------+ | 1 | 1 | 45 | 2016-05-10 | | 2 | 3 | 100 | 2016-05-13 | | 3 | 1 | 230 | 2016-05-14 | | 4 | 2 | 10 | 2016-05-14 | | 5 | 5 | 205 | 2016-05-14 | | 6 | 4 | 13 | 2016-05-15 | | 7 | 3 | 220 | 2016-05-15 | | 8 | 5 | 545 | 2016-05-16 | | 9 | 3 | 201 | 2016-05-17 | +-----+---------+-------+------------+ 9 rows in set (0.00 sec)
SQL HAVING 實(shí)例
現(xiàn)在我們想要查找總訪問量大于 200 的網(wǎng)站。
我們使用下面的 SQL 語(yǔ)句:
實(shí)例
SELECT
Websites
.
name
,
Websites
.
url
,
SUM
(
access_log
.
count
)
AS
nums
FROM
(
access_log
INNER
JOIN
Websites
ON
access_log
.
site_id
=
Websites
.
id
)
GROUP
BY
Websites
.
name
HAVING
SUM
(
access_log
.
count
)
>
200
;
執(zhí)行以上 SQL 輸出結(jié)果如下:
現(xiàn)在我們想要查找總訪問量大于 200 的網(wǎng)站,并且 alexa 排名小于 200。
我們?cè)?SQL 語(yǔ)句中增加一個(gè)普通的 WHERE 子句:
實(shí)例
SELECT
Websites
.
name
,
SUM
(
access_log
.
count
)
AS
nums
FROM
Websites
INNER
JOIN
access_log
ON
Websites
.
id
=
access_log
.
site_id
WHERE
Websites
.
alexa
<
200
GROUP
BY
Websites
.
name
HAVING
SUM
(
access_log
.
count
)
>
200
;
執(zhí)行以上 SQL 輸出結(jié)果如下:
本文標(biāo)題:創(chuàng)新互聯(lián)MSSQL教程SQLHAVING子句
當(dāng)前地址:http://m.5511xx.com/article/cdcsscs.html


咨詢
建站咨詢
