我有一个主表(table1)和一个明细表(table2),主表中存放的是人员的信息,明细表中存放是这些人员的考勤信息,如果在table2中有多少条记录,就表示此人出勤多少天。我想统计每个人的出勤天数,生成一个表,请问这个sql语句应该如何写?两个表的结构:
table1:   
   id
   nametable2:
   idtable1中记录: id   name
001   name1  
002   name2  
003   name3
table2中记录: id   
001  
002  
002
003
003达到的统计效果:id    出勤天数
001     1
002     2
003     2

解决方案 »

  1.   

    select table1.id,sum(table2.id) from table1.id = table2.id
    group by table1.id
      

  2.   

    select 
      a.id,
      isnull(count(b.id),0) as 出勤天数
    from table1 a,table2 b
    where a.id=b.id
    group by a.id
      

  3.   

    ---测试数据---
    if object_id('[table1]') is not null drop table [table1]
    go
    create table [table1]([id] varchar(3),[name] varchar(5))
    insert [table1]
    select '001','name1' union all
    select '002','name2' union all
    select '003','name3'
    if object_id('[table2]') is not null drop table [table2]
    go
    create table [table2]([id] varchar(3))
    insert [table2]
    select '001' union all
    select '002' union all
    select '002' union all
    select '003' union all
    select '003'
     
    ---查询---
    select 
      a.id,
      isnull(count(b.id),0) as 出勤天数
    from table1 a,table2 b
    where a.id=b.id
    group by a.id---结果---
    id   出勤天数        
    ---- ----------- 
    001  1
    002  2
    003  2(所影响的行数为 3 行)
      

  4.   

    谢谢各位!josy说得有道理,我试试。
      

  5.   

    如果我要输出以下结果呢?id    name   出勤天数 
    001   name1   1 
    002   name2   2 
    003   name3   2 我写成如下格式:
    select 
      a.id,a.name,
      isnull(count(b.id),0) as 出勤天数
    from table1 a,table2 b
    where a.id=b.id
    group by a.id运行时提示错误:
     “选择列表中的列 'a.name'无效,因为该列没有包含在聚合函数或 GROUP BY 子句中。”请问如何处理?
      

  6.   

    按楼上的方法可以实现,如果我要显示table1中几个字段,那么是否就必须要在group by 后面添加几个字段?
      

  7.   

    create table tb1(id varchar(3),name varchar(5))
    insert tb1
    select '001','name1' union all
    select '002','name2' union all
    select '003','name3'
    create table tb2(id varchar(3))
    insert tb2
    select '001' union all
    select '002' union all
    select '002' union all
    select '003' union all
    select '003'--如果不考虑不存在完全缺勤的情况
    select tb1.id , count(*) cnt from tb1 , tb2 where tb1.id = tb2.id group by tb1.id
    /*
    id   cnt         
    ---- ----------- 
    001  1
    002  2
    003  2(所影响的行数为 3 行)
    */--如果考虑存在完全缺勤的情况
    select tb1.id , isnull(n.cnt,0) cnt from tb1 left join (select count(*) cnt, id from tb2 group by id) n on tb1.id = n.id
    /*
    id   cnt         
    ---- ----------- 
    001  1
    002  2
    003  2(所影响的行数为 3 行)
    */drop table tb1 , tb2