a表:id,name,date
b表:id,a_id(外键)
我现在查找a表中每天的总数,和安装了b的记录数,未安装b的记录数比如a表记录
1,name1,2013-9-08
2, name2,2013-9-08
3,name3,2013-9-10
2, name4,2013-9-11
b表记录
1,1
2,3
那我要查的总记录数为2,安装了b的记录数为1
日期 总记录数 安装数 未安装数
2013-9-8 2 1 1
2013-9-10 1 1 0
2013-9-11 1 0 1
b表:id,a_id(外键)
我现在查找a表中每天的总数,和安装了b的记录数,未安装b的记录数比如a表记录
1,name1,2013-9-08
2, name2,2013-9-08
3,name3,2013-9-10
2, name4,2013-9-11
b表记录
1,1
2,3
那我要查的总记录数为2,安装了b的记录数为1
日期 总记录数 安装数 未安装数
2013-9-8 2 1 1
2013-9-10 1 1 0
2013-9-11 1 0 1
if object_id('Tempdb..#a') is not null drop table #a
if object_id('Tempdb..#b') is not null drop table #b
create table #a(
[id] int identity(1,1) not null,
[name] nvarchar(100) null,
[date] datetime null
)create table #b(
[id] int identity(1,1) not null,
[a_id] int null
)
Insert Into #a
select 'name1','2013-9-08' union all
select 'name2','2013-9-08' union all
select 'name3','2013-9-10' union all
select 'name4','2013-9-11'
Insert Into #b
select 1 union all
select 3
--查询
select convert(varchar(10),a.date,120) as 日期,count(1) as 总记录,sum(case when a.id=b.a_id then 1 else 0 end) as 安装记录数,
sum(case when b.a_id is null then 1 else 0 end) as 未安装记录数
from #a a left join #b b on a.id=b.a_id
group by a.date
-----------------
(4 行受影响)(2 行受影响)
日期 总记录 安装记录数 未安装记录数
---------- ----------- ----------- -----------
2013-09-08 2 1 1
2013-09-10 1 1 0
2013-09-11 1 0 1(3 行受影响)
select t.*,(t.[总记录数]-t.[安装数]) as [未安装数] from (
select [date] as [日期],COUNT(*) as [总记录数],sum ( case when a_id is null then 1 else 0 end) as [安装数]
from #a
left join #b on #a.id=#b.a_id
group by [date]
)t