日期:2014-05-17  浏览次数:20473 次

想做个柱状图按月统计收入和支出,收入和支出的数据分别放在A,B两个表中,表中的字段有金额和日期
现在通过查询数据库,不知道该怎么查询了,是不是要新建一个表装数据,还是写个存储过程啊?望大家指点指点。

------解决方案--------------------
if OBJECT_ID('A')is not null drop table A
create table A
(
income money,
[date] datetime
)
go
if OBJECT_ID('B')is not null drop table B
create table B
(
outcome money,
[date] datetime
)

insert into A
select 20,'2013-5-1' union
select 30,'2013-5-2'union
select 40,'2013-5-3'union
select 50,'2013-5-4'union
select 20,'2013-4-1'union
select 30,'2013-4-2'union
select 40,'2013-4-3'union
select 60,'2013-5-4'
go

insert into B
select 20,'2013-5-1'union
select 30,'2013-5-2'union
select 40,'2013-5-3'union
select 50,'2013-5-4'union
select 20,'2013-4-1'union
select 30,'2013-4-2'union
select 40,'2013-4-3'union
select 60,'2013-5-4'

with cte
as
(
select convert(varchar(6),A.date,112) date,sum(A.income) income
from 
A
group by
convert(varchar(6),A.date,112)
),
cte1
as
(
select convert(varchar(6),B.date,112) date,sum(B.outcome) outcome
from 
B
group by
convert(varchar(6),B.date,112)
)

select cte.date,cte.income,cte1.outcome
from
cte inner join cte1 on cte.date=cte1.date