2013-04-02 71 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 
爲例