a表:id,name
b表:id,a_id(外键)
我现在要查a表中安装了b的记录数比如a表记录 
1,name1
2,  name2
b表记录
1,1
那我要查的总记录数为2,安装了b的记录数为1必须一条SQL语句搞定, 谢谢了sql

解决方案 »

  1.   

    select COUNT(*) as 总记录,(select COUNT(*) from b where a.id=b.a_id) as 安装记录数
    from a
      

  2.   

    select count(A.ID)
    from A join B on A.ID = B.a_id是不是这意思
      

  3.   

    ;with a(id,name) as
    (
    select 1,'name1'
    union all select 2,'name2'
    ),
    b(id,a_id) as
    (
    select 1,1
    )
    select COUNT(*) as 总记录,(select COUNT(b.a_id) from b inner join a on a.id=b.a_id) 安装记录数
    from a
      

  4.   

    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
    )create table #b(
    [id] int identity(1,1) not null,
    [a_id] int null
    )--a表插入6条记录
    Insert Into #a
    select 'name1' union all
    select 'name2' union all
    select 'name3' union all
    select 'name4' union all
    select 'name5' union all
    select 'name6'--b表插入5条记录
    Insert Into #b
    select 1 union all
    select 2 union all
    select 3 union all
    select 4 union all
    select 5   
    --查询
    select count(1) as 总记录,sum(case when a.id=b.a_id then 1 else 0 end) as 安装b记录数
    from #a a left join #b b on a.id=b.a_id
    -------------(6 行受影响)(5 行受影响)
    总记录         安装b记录数
    ----------- -----------
    6           5(1 行受影响)