SQLÖÐ groupbyºÍhavingµÄÇø±ð
½éÉÜGROUP BY ºÍ HAVING ×Ó¾äÇ°£¬ÎÒÃDZØÐèÏȽ²½²sqlÓïÑÔÖÐÒ»ÖÖÌØÊâµÄº¯Êý:¾ÛºÏº¯Êý£¬ÀýÈçSUM, COUNT, MAX, AVGµÈ¡£ÕâЩº¯ÊýºÍÆäËüº¯ÊýµÄ¸ù±¾Çø±ð¾ÍÊÇËüÃÇÒ»°ã×÷ÓÃÔÚ¶àÌõ¼Ç¼ÉÏ¡£
SELECT SUM(population) from bbc
ÕâÀïµÄSUM×÷ÓÃÔÚËùÓзµ»Ø¼Ç¼µÄpopulation×Ö¶ÎÉÏ£¬½á¹û¾ÍÊǸòéѯֻ·µ»ØÒ»¸ö½á¹û£¬¼´ËùÓйú¼ÒµÄ×ÜÈË¿ÚÊý¡£
ͨ¹ýʹÓÃGROUP BY ×Ӿ䣬¿ÉÒÔÈÃSUM ºÍ COUNT ÕâЩº¯Êý¶ÔÊôÓÚÒ»×éµÄÊý¾ÝÆð×÷Óᣵ±ÄãÖ¸¶¨ GROUP BY region ʱ£¬ ÊôÓÚͬһ¸öregion(µØÇø)µÄÒ»×éÊý¾Ý½«Ö»ÄÜ·µ»ØÒ»ÐÐÖµ£¬Ò²¾ÍÊÇ˵£¬±íÖÐËùÓгýregion(µØÇø)ÍâµÄ×ֶΣ¬Ö»ÄÜͨ¹ý SUM, COUNTµÈ¾ÛºÏº¯ÊýÔËËãºó·µ»ØÒ»¸öÖµ¡£
HAVING×Ó¾ä¿ÉÒÔÈÃÎÒÃÇɸѡ³É×éºóµÄ¸÷×éÊý¾Ý£¬WHERE×Ó¾äÔÚ¾ÛºÏÇ°ÏÈɸѡ¼Ç¼.Ò²¾ÍÊÇ˵×÷ÓÃÔÚGROUP BY ×Ó¾äºÍHAVING×Ó¾äÇ°.
¶ø HAVING×Ó¾äÔھۺϺó¶Ô×é¼Ç¼½øÐÐɸѡ¡£
ÈÃÎÒÃÇ»¹ÊÇͨ¹ý¾ßÌåµÄʵÀýÀ´Àí½âGROUP BY ºÍ HAVING ×Ӿ䣬»¹²ÉÓõÚÈý½Ú½éÉܵÄbbc±í¡£
SQLʵÀý:
Ò»¡¢ÏÔʾÿ¸öµØÇøµÄ×ÜÈË¿ÚÊýºÍ×ÜÃæ»ý: SELECT region, SUM(population), SUM(area)
from bbc
GROUP BY region
ÏÈÒÔregion°Ñ·µ»Ø¼Ç¼·Ö³É¶à¸ö×飬Õâ¾ÍÊÇGROUP BYµÄ×ÖÃ溬Òå¡£·ÖÍê×éºó£¬È»ºóÓþۺϺ¯Êý¶Ôÿ×éÖеIJ»Í¬×Ö¶Î(Ò»»ò¶àÌõ¼Ç¼)×÷ÔËËã¡£
¶þ¡¢ ÏÔʾÿ¸öµØÇøµÄ×ÜÈË¿ÚÊýºÍ×ÜÃæ»ý.½öÏÔʾÄÇЩÃæ»ý³¬¹ý1000000µÄµØÇø¡£ SELECT region, SUM(population), SUM(area)
from bbc
GROUP BY region
HAVING SUM(area)>1000000
ÔÚÕâÀÎÒÃDz»ÄÜÓÃwhereÀ´É¸Ñ¡³¬¹ý1000000µÄµØÇø£¬ÒòΪ±íÖв»´æÔÚÕâÑùÒ»Ìõ¼Ç¼¡£
Ïà¹ØÎĵµ£º
Êý¾Ý¿â£º
1¡¢ ´´½¨Êý¾Ý¿âµÄÓï·¨£º
if exists (select * from sysdatabases where name='DT_name') /*ÅжÏÊÇ·ñ´æÔÚ£¬ÊÇÔòɾ³ý*/
drop database DT_name
create database database_name
on primary /* Ö¸¶¨Ö÷ÒªÎļþ×飬ÆäÖеÚÒ»¸öÖ÷ÒªÎļþ * ......
Ðл»ÁУº
--> Éú³É²âÊÔÊý¾Ý±í: [tb]
IF OBJECT_ID('[tb]') IS NOT NULL
DROP TABLE [tb]
GO
CREATE TABLE [tb] ([a] [int],[b] [int],[c] [int])
INSERT INTO [tb]
SELECT '3','9','5' UNION ALL
SELECT '5','2','7' UNION ALL
SELECT '6','3','8'
--SELECT * from [tb]
-->SQL²éѯÈçÏ ......
USE master
GO
DECLARE @dbname sysname
SET @dbname='TEST' --Õâ¸öÊÇҪɾ³ýµÄÊý¾Ý¿â¿âÃû
DECLARE @s NVARCHAR(1000)
DECLARE tb CURSOR local FOR
SELECT s='KILL '+CAST(spid AS NVARCHAR)&nbs ......
--
> ²âÊÔÊý¾Ý£º[tb]
if
object_id
(
'
[tb]
'
)
is
not
null
drop
table
[
tb
]
go
create
table
[
tb
]
(
[
id
]
int
,
[
lx
]
int
)
insert
[
tb
]
select
29
,
2
union
all
select
30
,
3
union
all
sel ......
×ÔÁ¬½ÓÊÇÖ¸Ò»¸ö±íÓëÆä×ÔÉí½øÐÐÁ¬½Ó¡£
¾ÙÒ»¸ö¼òµ¥µÄʵÀý£¬Ò»¸öѧÉú¿Î³Ì³É¼¨±íStudentScore£¬ÆäÖаüÀ¨Ñ§Éú±àºÅ/studentid£¬ËùÑ¡¿Î³Ì/coursename,¿Î³Ì³É¼¨/score
Ñ¡ÔñÿÃſγ̵ÄÇ°Á½ÃûѧÉú,²¢½«ËûÐÅÏ¢Êä³ö³öÀ´
´ËʱÄãµÄµÚÒ»·´Ó¦¾ÍÊÇÒª°ÑѧÉú°´ËùÑ¡¿Î³Ì½øÐзÖ×飬Ȼºó±È½Ï»ñµÃÿÃſγÌÀïÃæÇ°Á½Î»µÄѧÉú
·Ö×éµÄ·½Ê½ÓÐgroup b ......