今天看到一个数据库查询结果问题
有一个表shouru 字段包括单位名称,收入,收入日期
还有一个表xiaoshou 字段包括单位名称,销售,销售日期
要求查询出结果是这样的
单位名称 一月 二月 。 十一月 十二月
收入 销售 收入 销售 收入 销售 收入 销售请各位来告诉我该怎么写啊,这个sql语句啊
有一个表shouru 字段包括单位名称,收入,收入日期
还有一个表xiaoshou 字段包括单位名称,销售,销售日期
要求查询出结果是这样的
单位名称 一月 二月 。 十一月 十二月
收入 销售 收入 销售 收入 销售 收入 销售请各位来告诉我该怎么写啊,这个sql语句啊
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.单位名称
;
就像用excel一样,一个列还区分成几个子项
,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.单位名称
;
'收入 '||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.单位名称
然后单位名称做横列,月份,收入类型做纵列,金额放到值列表就可以了.
用这个测试了一下,出现如下错误
where a.单位名称=b.单位名称 and to_char(a.收入日期,'mm')=to_char(b.销售日期,'mm')
*
ERROR 位于第 4 行:
ORA-01722: 无效数字销售表里有销售日期字段啊, 怎么回事呢
to_char(a.收入日期,'mm')=to_char(b.销售日期,'mm')