建表數據庫
create table waw_school
(
id int identity(1,1) primary key,
name nvarchar(60),
age tinyint,
phone bigint,
hobby nvarchar(512),
note nvarchar(1024),
utime datetime default getdate()
);ide
create table waw_class
(
id int identity(1,1) primary key ,
school_id int,
name nvarchar(60),
note nvarchar(1024),
utime datetime default getdate()
)spa
----------------------------------------------------------------事件
《一》distinct在查詢時候用到,用於對查詢結果排重
select distinct school_id from waw_class
等同於
select school_id from waw_class
group by school_id內存
《二》子查詢:在查詢中,子查詢結果集用於外圍查詢的限制條件
select * from waw_class a
where a.school_id in (select id from waw_school where name = 'zsq')
或
select * from waw_class a
where exists (select * from waw_school b where a.school_id = b.id and b.id = 1)
或
select * from waw_class a
where not exists (select * from waw_school b where a.school_id = b.id and b.id = 2)開發
《三》基於列的邏輯表達式
select a.id ,
a.school_id ,
case when a.school_id = 1 then 'zsq' when a.school_id = 2 then 'zxn' end as school,
a.name,a.note,a.utime
from waw_class aget
《四》關於分組(group by)對於須要根據不一樣緯度統計時,只用group by就會很麻煩,例如:it
下邊我結合我在實際開發中的例子,提出新的解決方案:table
--a,b,c abc ab aclass
SELECT CAST(a.採集時間 AS DATE) AS 發佈時間,a.正負面,a.信息類型,COUNT(1) FROM 監測執行表 a WITH(NOLOCK)
WHERE a.事件ID = 2014095560 AND a.採集時間 > '2017-05-10'
GROUP BY ROLLUP (CAST(a.採集時間 AS DATE),a.正負面,a.信息類型)
--a,b,c abc ab ac bc a b c
SELECT CAST(a.採集時間 AS DATE) AS 發佈時間,ISNULL(a.正負面,'中性') AS 正負面,ISNULL(a.信息類型,4) 信息類型,COUNT(1) FROM 監測執行表 a WITH(NOLOCK)
WHERE a.事件ID = 2014095560 AND a.採集時間 > '2017-05-10'
GROUP BY CUBE (CAST(a.採集時間 AS DATE),ISNULL(a.正負面,'中性'),ISNULL(a.信息類型,4) )
--a,b,c a bc
SELECT CAST(a.採集時間 AS DATE) AS 發佈時間,ISNULL(a.正負面,'中性') AS 正負面,ISNULL(a.信息類型,4) 信息類型,COUNT(1) FROM 監測執行表 a WITH(NOLOCK)
WHERE a.事件ID = 2014095560 AND a.採集時間 > '2017-05-10'
GROUP BY GROUPING SETS (CAST(a.採集時間 AS DATE),(ISNULL(a.正負面,'中性'),ISNULL(a.信息類型,4) ) )
注意: 使用GROUPING SETS僅僅是一個能夠少寫些代碼的語法糖.但實際狀況是,GROUPING SETS在遇到多個條件時,聚合是一次性從數據庫中取出全部須要操做的數據,在內存中對數據庫進行聚合操做並生成結果。而UNION ALL是屢次掃描表,將返回的結果進行UNION操做