查询a,b,c三个表,a表有字段id,c表有aid是外键到a表,c表haiyoudt时间字段和state字段,正常情况下我根据state查询出来的只有yigedt字段,但是我现在想根据state3个状态查询3个dt字段的值,显示在3列

解决方案 »

  1.   

    select 时间 as 时间 ,
      max(case 状态 when 'A' thenT.状态 else '' end) A,
      max(case 状态 when 'B' then T.状态 else '' end) B,
      max(case 状态 when 'C' then T.状态 else '' end) C
    from tb
    left join [sign] T on T.id = tb.id  --外链的表
    group by 时间类似这样。
      

  2.   

    select c.haiyoudt as 时间 ,
      max(case c.state when 'A' then c.state else '' end) A,
      max(case c.state when 'B' then c.state else '' end) B,
      max(case c.state when 'C' then c.state else '' end) C
    from a
    left join c  on c.aid = a.id  --外链的表
    where c.state = '要查的类型'
    group by c.haiyoudt
    --A B C 代替你要显示为列的值,可以自己扩展一下
      

  3.   


    现在这样只能查询state一种状态,我怎么才能同时查询3种状态呢?
      

  4.   

    select c.haiyoudt as 时间 ,
      max(case c.state when 'A' then c.state else '' end) A,
      max(case c.state when 'B' then c.state else '' end) B,
      max(case c.state when 'C' then c.state else '' end) C
    from a
    left join c  on c.aid = a.id  --外链的表
    where c.haiyoudt >'2014-01-01'   --设定时间查找即可
    group by c.haiyoudt
      

  5.   

    我想再根据ABC获取AB的sum怎么获取啊?也是单独在一个列
      

  6.   

    select c.haiyoudt as 时间 ,
      max(case c.state when 'A' then c.state else '' end) A,
      max(case c.state when 'B' then c.state else '' end) B,
      max(case c.state when 'C' then c.state else '' end) C,
    sum(case when c.state in ('A','B') then  c.state else '' end) as 'AB sum'
    from a
    left join c  on c.aid = a.id  --外链的表
    where c.haiyoudt >'2014-01-01'   --设定时间查找即可
    group by c.haiyoudt参考