今天看到一个数据库查询结果问题
有一个表shouru 字段包括单位名称,收入,收入日期
还有一个表xiaoshou 字段包括单位名称,销售,销售日期
要求查询出结果是这样的
单位名称    一月           二月     。  十一月    十二月
           收入 销售     收入  销售                收入 销售   收入 销售请各位来告诉我该怎么写啊,这个sql语句啊
  

解决方案 »

  1.   


    select a.单位名称
           ,sum(case when a.收入日期='一月' then a.收入 end)  一月收入
           ,sum(case when b.销售日期='一月' then b.销售 end)  一月销售
           ,sum(case when a.收入日期='二月' then a.收入 end)  二月收入
           ,sum(case when b.销售日期='二月' then b.销售 end)  二月销售
           ,sum(case when a.收入日期='三月' then a.收入 end)  三月收入
           ,sum(case when b.销售日期='三月' then b.销售 end)  三月销售
           ...
    from shouru a,xiaoshou b
    where a.单位名称=b.单位名称
    group by a.单位名称
    ;
      

  2.   

    人家可能是要做个报表
    就像用excel一样,一个列还区分成几个子项
      

  3.   

    select a.单位名称
           ,sum(case when to_char(a.收入日期,'mm')='01' then a.收入 end)  一月收入
           ,sum(case when to_char(b.销售日期,'mm')='01' then b.销售 end)  一月销售
           ...
    from shouru a,xiaoshou b
    where a.单位名称=b.单位名称 and to_char(a.收入日期,'yyyy')='2010' and to_char(b.销售日期,'yyyy')='2010'
    group by a.单位名称
    ;
      

  4.   

    select a.单位名称,
    '收入 '||sum(decode(to_char(a.收入日期,'mm'),'01',a.收入))||' '||'销售 '||sum(decode(to_char(b.销售日期,'mm'),'01',b.销售)) "一月",
    ....
    '收入 '||sum(decode(to_char(a.收入日期,'mm'),'12',a.收入))||' '||'销售 '||sum(decode(to_char(b.销售日期,'mm'),'12',b.销售)) "十二月"
    from shouru a,xiaoshou b
    where a.单位名称=b.单位名称 and to_char(a.收入日期,'mm')=to_char(b.销售日期,'mm')
    group by a.单位名称
      

  5.   

    仔细看了下,你这个直接用sql没法得到结果,需要使用交叉表.
      

  6.   

    先用group by生成 单位名称,月份,收入类型(收入,销售),金额 这样形式的基础表,
    然后单位名称做横列,月份,收入类型做纵列,金额放到值列表就可以了.
      

  7.   


    用这个测试了一下,出现如下错误
    where a.单位名称=b.单位名称 and to_char(a.收入日期,'mm')=to_char(b.销售日期,'mm')
                                                                     *
    ERROR 位于第 4 行:
    ORA-01722: 无效数字销售表里有销售日期字段啊, 怎么回事呢
      

  8.   

    两个表的日期是什么字段 不是date的要转为date
    to_char(a.收入日期,'mm')=to_char(b.销售日期,'mm')