日期:2014-05-19  浏览次数:20607 次

求如下sql语句
数据表1:
类型,名称,数量,金额,       时间
a         x1         5         700         2007-01-01
a         x2         10       1400       2007-01-02
b         x3         6         700         2007-01-02
c         x4         9         600         2007-01-03
..........

表2:
金额,         时间
500           2007-01-01
400           2007-01-02
300           2007-01-02
400           2007-01-03
.............


要求生成表3
日期,             a数量,a金额,b数,b金,c数,c金,本日合计,本日收款,本日结算
2007-01-01     5             700         0           0           0         0           700         500                 200
2007-01-02     10           1400       6           700       0         0           2100       700               1400
2007-01-03     0                 0         0           0           9         600       600         400                 200
2007-01-04     0                 0         0           0           0         0           0             0                     0
........

------解决方案--------------------
没测试过:
表ta:
类型,名称,数量,金额, 时间
a x1 5 700 2007-01-01
a x2 10 1400 2007-01-02
b x3 6 700 2007-01-02
c x4 9 600 2007-01-03

declare @s varchar(4000)
set @s= ' '
select @s=@s+ ', '+quotename(类型+ '数量 ')+ '=sum(case when 类型= '+quotename(类型, ' ' ' ')+
' then 数量 else 0 end), '+
quotename(类型+ '金额 ')+ '=sum(case when 类型= '+quotename(类型, ' ' ' ')+
' then 金额 else 0 end) '
from ta
group by 类型

set @s= 'select [日期]=convert(varchar(10),时间,120) '+@s+ ' from ta group by convert(varchar(10),时间,120) '

exec(@s)
------解决方案--------------------


--测试表
create table 表1(类型 varchar(10),名称 varchar(10),数量 int,金额 int,时间 datetime)
create table 表2(金额 int,时间 datetime)

insert 表1 select 'a ', 'x1 ', 5, 700 , '2007-01-01 '
union all
select 'a ' , 'x2 ' , 10 , 1400 , '2007-01-02 '
union all
select 'b &