请教这个子查询应该怎么改?
请教这个子查询应该怎么改?
select 期初数量=tmp.进货量+tmp.调入量+tmp.销售总额-tmp.进货退货量-tmp.调出量-tmp.销售量,期初金额=tmp.进货总额+ tmp.调入总额+tmp.销售退货总额-tmp.进货退货总额-tmp.调出总额-tmp.销售总额 from
(
--查询日期前进货和进货退货量,及其总额
(Select sum(case 类型 when '进货单' then 数量 else 0 end) As 进货量,
sum(case 类型 when '进货单' then 数量*单价 else 0 end) As 进货总额,
sum(Case 类型 When '进货退货单' Then 数量 Else 0 End) As 进货退货量,
sum(case 类型 when '进货退货单' then 数量*单价 else 0 end) As 进货退货总额
From 进货退货 Where 日期 < @StartDate),
--查询日期前调入,调出量,及其总额
(Select sum(case 类型 when '调入单' then 数量 else 0 end) As 调入量,
sum(case 类型 when '调入单' then 数量*单价 else 0 end) As 调入总额,
sum(Case 类型 When '调出单' Then 数量 Else 0 End) As 调出量,
sum(case 类型 when '调出单' then 数量*单价 else 0 end) As 调出总额
From 调拨 Where 日期< @StartDate),
--查询日期前销售,销售退货量,及其总额
(Select sum(销售量) as 销售量,sum(销售量*单价) as 销售总额,sum(销售退货) as 销售退货量,sum(销售退货*单价) as 销售退货总额 FROM 汇总单 where 日期 < @StartDate)
) tmp
------解决方案--------------------SQL code
select 期初数量=m.进货量+n.调入量+p.销售总额-m.进货退货量-n.调出量-n.销售量,期初金额=m.进货总额+ n.调入总额+p.销售退货总额-
m.进货退货总额-n.调出总额-p.销售总额 from
--查询日期前进货和进货退货量,及其总额
(Select sum(case 类型 when '进货单 ' then 数量 else 0 end) As 进货量,
sum(case 类型 when '进货单 ' then 数量*单价 else 0 end) As 进货总额,
sum(Case 类型 When '进货退货单 ' Then 数量 Else 0 End) As 进货退货量,
sum(case 类型 when '进货退货单 ' then 数量*单价 else 0 end) As 进货退货总额
From 进货退货 Where 日期 < @StartDate) m,
--查询日期前调入,调出量,及其总额
(Select sum(case 类型 when '调入单 ' then 数量 else 0 end) As 调入量,
sum(case 类型 when '调入单 ' then 数量*单价 else 0 end) As 调入总额,
sum(Case 类型 When '调出单 ' Then 数量 Else 0 End) As 调出量,
sum(case 类型 when '调出单 ' then 数量*单价 else 0 end) As 调出总额
From 调拨 Where 日期 < @StartDate) n,
--查询日期前销售,销售退货量,及其总额
(Select sum(销售量) as 销售量,sum(销售量*单价) as 销售总额,sum(销售退货) as 销售退货量,sum(销售退货*单价) as 销售退货总额 FROM 汇总单 where 日期 < @StartDate) p