2013-04-02 69 views
-1

变量是否有无法使用的“为[项目],然后在查询中使用的项目变量查询,子查询,并使用从子查询

,例如:

select c.category as [category],c.orderby as [CatOrder], m.masterno, m.master 
,-- select OUT (select count(*) from rentalitem  ri with (nolock), 
      rentalitemstatus ris with (nolock), 
      rentalstatus  rs with (nolock) 
    where ri.rentalitemid = ris.rentalitemid 
      and ris.rentalstatusid = rs.rentalstatusid 
      and ri.masterid  = m.masterid 
      and rs.statustype  in ('OUT', 'INTRANSIT', 'ONTRUCK')) as [qtyout] 
,-- select OWNED owned= 
(select top 1 mwq.qty           
    from masterwhqty mwq            
    where mwq.masterid = m.masterid) 

, -([owned]-[qtyout]) as [Variance] 

from master m 
    inner join category c on c.categoryid=m.categoryid and [email protected] 
    inner join inventorydepartment d on [email protected] 

我不能似乎计算方差时使用qtyout或拥有。我该怎么办呢?

回答

1

需要将您的计算字段为子查询,然后通过自己的别名,在外部查询中使用它们。

select subquery.*, -([owned]-[qtyout]) as [Variance] 
from 
(
    select c.category as [category],c.orderby as [CatOrder], m.masterno, m.master 
    ,-- select OUT (select count(*) from rentalitem  ri with (nolock), 
       rentalitemstatus ris with (nolock), 
       rentalstatus  rs with (nolock) 
     where ri.rentalitemid = ris.rentalitemid 
       and ris.rentalstatusid = rs.rentalstatusid 
       and ri.masterid  = m.masterid 
       and rs.statustype  in ('OUT', 'INTRANSIT', 'ONTRUCK')) as [qtyout] 
    ,-- select OWNED owned= 
    (select top 1 mwq.qty           
     from masterwhqty mwq            
     where mwq.masterid = m.masterid) as [owned] 

    from master m 
     inner join category c on c.categoryid=m.categoryid and [email protected] 
     inner join inventorydepartment d on [email protected] 
) as subquery 
0

你需要使用子查询:

select t.*, 
     ([owned]-[qtyout]) as [Variance] 
from (<something like your query here 
    ) t 

您查询,即使没有评论,并不完全意义(select OUT (select . . .为isntance)。但是,您的问题的答案是在子查询或CTE中定义基本变量,然后使用它们。

而且,您称之为差异“差异”。大家知道,您正在重新定义术语(http://en.wikipedia.org/wiki/Variance)的统计含义,该术语基于差异的平方。

2

你也可以使用一个表变量,然后引用该表变量像你尝试上述做....这里是从MSDN

USE AdventureWorks2012; 
GO 
DECLARE @MyTableVar table(
    EmpID int NOT NULL, 
    OldVacationHours int, 
    NewVacationHours int, 
    ModifiedDate datetime); 
UPDATE TOP (10) HumanResources.Employee 
SET VacationHours = VacationHours * 1.25, 
    ModifiedDate = GETDATE() 
OUTPUT inserted.BusinessEntityID, 
     deleted.VacationHours, 
     inserted.VacationHours, 
     inserted.ModifiedDate 
INTO @MyTableVar; 
--Display the result set of the table variable. 
SELECT EmpID, OldVacationHours, NewVacationHours, ModifiedDate 
FROM @MyTableVar; 
GO 
--Display the result set of the table. 
SELECT TOP (10) BusinessEntityID, VacationHours, ModifiedDate 
FROM HumanResources.Employee; 
GO 
为例