前面几篇文章作为自己的读书笔记(SQL Server 2005技术内幕:查询、调整和优化),基本都是书上的内容,没敢放在首页上。现在学习SQL Server都是理论知识,自己有个习惯,一直看理论看下去不容易吸收,所以看到“聚合”这一节决定写写代码,用来加深对SQL Server执行计划的理解。
首先看看我在在SQL Server中是怎么处理连接查询和分组查询的。
--建表
if OBJECT_ID('tableA') is not null
drop table tableA
Create table tableA(
ID int identity primary key,
Name varchar(30)
)
if OBJECT_ID('tableB') is not null
drop table tableB
Create table tableB(
ID int,
summary varchar(30)
)
--插入测试数据
insert into tableA(Name) select 'A' union all select 'B' union all select 'C'
insert into tableB(ID, summary)
select 1, 'test-001' union all
select 1, 'test-002' union all
select 3, 'test-001' union all
select 4, 'test-001'
--左连接查询
select A.ID, A.Name, B.summary from tableA A left join tableB B on(A.ID = B.ID)
--根据ID分组查询
select ID, COUNT(1) number from tableB group by ID
if OBJECT_ID('tableA') is not null
drop table tableA
Create table tableA(
ID int identity primary key,
Name varchar(30)
)
if OBJECT_ID('tableB') is not null
drop table tableB
Create table tableB(
ID int,
summary varchar(30)
)
--插入测试数据
insert into tableA(Name) select 'A' union all select 'B' union all select 'C'
insert into tableB(ID, summary)
select 1, 'test-001' union all
select 1, 'test-002' union all
select 3, 'test-001' union all
select 4, 'test-001'
--左连接查询
select A.ID, A.Name, B.summary from tableA A left join tableB B on(A.ID = B.ID)
--根据ID分组查询
select ID, COUNT(1) number from tableB group by ID