日期:2014-05-18  浏览次数:20688 次

请问子查询里的某个字段的值是取自另外一个表的,该怎么写?
下面子查询里的单价是取自另外一个物品表的单价字段,该怎么写呢?

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

------解决方案--------------------
SQL code
--这样?
Select id , 
  sum(case 类型 when '进货单' then 数量*(select 单价 from C where id = a.id) else 0 end) As 进货总额 
From 进货退货 Where 日期  < @StartDate A 
group by id

------解决方案--------------------
SQL code

楼主改成这样试试:
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

------解决方案--------------------
SQL code

--这是你想要的结果吗?
--简单的测试
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