一个表一个字段有多种状态
table1
    is_repeat
    B
    C
    D
    T
    V
现在我想用一条SQL语句查出在B,C状态下的数量,和在BCDT状态下的数量,和总数量请问怎么做

解决方案 »

  1.   

    --這個?
    select 
    [數量BC]=(select count(*)from table1 where is_repeat in ('B','C')) ,
    [數量BCDT]=(select count(*) from table1 where is_repeat in ('B','C','D','T')),
    [總數量]=(select count(*) from table1)
      

  2.   

    create table table1(is_repeat char(1), num int)
    insert table1 select 
        'B',30
    union all select     'C',40
    union all select     'D',60
    union all select     'T',50
    union all select     'V',100
    union all select     'B',30
    union all select     'C',45
    union all select     'D',64
    union all select     'T',55
    union all select     'V',150select 
    B=sum(case when is_repeat='B' then num end),
    C=sum(case when is_repeat='C' then num end),
    BCDT=sum(case when is_repeat in('B', 'C', 'D', 'T') then num end)
    from table1--result
    B           C           BCDT        
    ----------- ----------- ----------- 
    60          85          374(1 row(s) affected)
      

  3.   

    用了case when,出错
    这是聚合
      

  4.   

    create table table1(is_repeat char(1))
    insert table1 select 'B'
    union all select     'C'
    union all select     'D'
    union all select     'T'
    union all select     'V'
    union all select     'B'
    union all select     'C'
    union all select     'D'
    union all select     'T'
    union all select     'D'
    union all select     'T'
    union all select     'V'select 
    B=sum(case when is_repeat='B' then 1 end),
    C=sum(case when is_repeat='C' then 1 end),
    BCDT=sum(case when is_repeat in('B', 'C', 'D', 'T') then 1 end)
     from  table1--result
    B           C           BCDT        
    ----------- ----------- ----------- 
    2           2           10(1 row(s) affected)
      

  5.   

    除了前面的方法外:select a.bc,b.bcdt,c.总数量 from
    (select count(*) as bc from tb where is_repeat in ('B','C')) a,
    (select count(*) as bcdt from tb where is_repeat in ('B','C','D','T')) b,
    (select count(*) as 总数量 from tb) c