下面子查询里的单价是取自另外一个物品表的单价字段,该怎么写呢?DECLARE @StartDate varchar(10)
DECLARE @EndDate varchar(10)set @StartDate='2006-01-01'
set @EndDate='2007-12-30'
select * from--查询日期前进货和进货退货量,及其总额
(Select sum(case 类型 when '进货单' then 数量*单价 else 0 end) As 进货总额 From 进货退货 Where 日期 < @StartDate) A,
(Select sum(case 类型 when '调入单' then 数量*单价 else 0 end) As 调入总额 From 调拨 Where 日期 < @StartDate) B
DECLARE @EndDate varchar(10)set @StartDate='2006-01-01'
set @EndDate='2007-12-30'
select * from--查询日期前进货和进货退货量,及其总额
(Select sum(case 类型 when '进货单' then 数量*单价 else 0 end) As 进货总额 From 进货退货 Where 日期 < @StartDate) A,
(Select sum(case 类型 when '调入单' then 数量*单价 else 0 end) As 调入总额 From 调拨 Where 日期 < @StartDate) B
Select id ,
sum(case 类型 when '进货单' then 数量*(select 单价 from C where id = a.id) else 0 end) As 进货总额
From 进货退货 Where 日期 < @StartDate A
group by id
(Select sum(case 类型 when '进货单' then 数量*(select 单价 from c where id = a.id) else 0 end) As 进货总额
From 进货退货 a Where 日期 < @StartDate group by id) m
full join
(Select sum(case 类型 when '调入单' then 数量*(select 单价 from c where id = a.id) else 0 end) As 调入总额
From 调拨 a Where 日期 < @StartDate group by id) n
on m.id = n.id
两个表的关联字段是 物品编号TO dawugui 我改成下面的这样,提示错误:
服务器: 消息 130,级别 15,状态 1,行 11
不能对包含聚合或子查询的表达式执行聚合函数。 DECLARE @StartDate varchar(10)
DECLARE @EndDate varchar(10)set @StartDate='2006-01-01'
set @EndDate='2007-12-30'
select * from--查询日期前进货和进货退货量,及其总额
(Select 商品编号, sum(case 类型 when '进货单' then 数量*(select 单价 from 物品资料 where 商品编号 = a.商品编号) else 0 end) As 进货总额 From 进货退货 Where 日期 < @StartDate) A GROUP BY 商品编号/*,
楼主改成这样试试:
DECLARE @StartDate varchar(10)
DECLARE @EndDate varchar(10) set @StartDate= '2006-01-01 '
set @EndDate= '2007-12-30 'select * from
--查询日期前进货和进货退货量,及其总额
(Select sum(case 类型 when '进货单 ' then 数量*b.单价 else 0 end) As 进货总额 From 进货退货,物品资料 b Where 日期 < @StartDate and 商品编号 = b.商品编号) A,
(Select sum(case 类型 when '调入单 ' then 数量*b.单价 else 0 end) As 调入总额 From 调拨,物品资料 b Where 日期 < @StartDate and 商品编号 = b.商品编号) B
--这是你想要的结果吗?
--简单的测试
declare @t table(id int,lx varchar(20),sl int,dj float,sj varchar(20))
insert into @t
select 1,'jin',10,10,'20070101'
union all select 2,'jin',20,11,'20070101'
union all select 3,'jin',12,12,'20070101'
union all select 4,'ru',55,14,'20070101'
declare @b table(id int,lx varchar(20),sl int,sj varchar(20))
insert into @b
select 1,'diao',5,'20071011'
union all select 2,'diao',7,'20071012'
union all select 4,'diao',10,'20071015'declare @m varchar(20)
declare @n varchar(20)
set @m='20071010'
set @n='20071012'select a.id, sum(case when a.lx = 'jin' and a.sj <@m then a.sl*a.dj else 0 end) 'jze',
sum(case when b.lx ='diao' and b.sj>@n then b.sl*a.dj else 0 end) 'dze'from @t a left join @b b on a.id=b.id group by a.id