存储过程中的子查询

时间:2013-07-02 09:59:30

标签: sql-server stored-procedures

我在sql存储过程中有一个查询。我希望从其ID中获取其他查询的记录。

SELECT t.Name ,t.CreatedDate ,t.CreatedBy , t.Amount
      ,t.Margin ,t.Probability ,t.Id 
FROM (SELECT a = 1) a 
CROSS JOIN 
    (SELECT 
        Name = HirschInternational_MSCRM.dbo.SalesOrderBase.Name 
       ,CreatedDate=HirschInternational_MSCRM.dbo.SalesOrderBase.CreatedOn 
       ,CreatedBy=HirschInternational_MSCRM.dbo.SystemUserBase.FullName
       ,Amount = totalamount 
       ,Probability=CloseProbability 
       ,Id=SalesOrderId
       ,Margin=(SELECT ( ISNULL( ((Sum(Price)-Sum(CurrentCost)) / NULLIF( Sum(Price), 0 ))*100, 0 ) ) 
                FROM HirschInternational_MSCRM.dbo.ProductBase 
                JOIN HirschInternational_MSCRM.dbo.SalesOrderDetailBase 
                  ON HirschInternational_MSCRM.dbo.SalesOrderDetailBase.ProductId = HirschInternational_MSCRM.dbo.ProductBase.ProductId 
                JOIN HirschInternational_MSCRM.dbo.SalesOrderBase 
                  ON HirschInternational_MSCRM.dbo.SalesOrderBase.SalesOrderId = HirschInternational_MSCRM.dbo.SalesOrderDetailBase.SalesOrderId)
     FROM HirschInternational_MSCRM.dbo.SalesOrderBase 
     JOIN HirschInternational_MSCRM.dbo.OpportunityBase 
       ON HirschInternational_MSCRM.dbo.SalesOrderBase.Opportunityid = HirschInternational_MSCRM.dbo.OpportunityBase.Opportunityid 
     JOIN HirschInternational_MSCRM.dbo.SystemUserBase 
       ON HirschInternational_MSCRM.dbo.SystemUserBase.SystemUserId = HirschInternational_MSCRM.dbo.SalesOrderBase.CreatedBy
    WHERE YEAR(HirschInternational_MSCRM.dbo.SalesOrderBase.CreatedOn)=YEAR(GETDATE())

我想从每个我希望输出的记录中获得保证金 enter image description here

2 个答案:

答案 0 :(得分:0)

目前还不完全清楚你想要什么,但你可能正在寻找像

这样的东西
select *
from (your SQL SELECT statement goes here) t1
where id = ?;

答案 1 :(得分:0)

我想获得每条记录的保证金,我如何过滤SalesOrderId的保证金查询 像

Margin=(SELECT ( ISNULL( ((Sum(Price)-Sum(CurrentCost)) / NULLIF( Sum(Price), 0 ))*100, 0 ) ) 
                FROM HirschInternational_MSCRM.dbo.ProductBase 
                JOIN HirschInternational_MSCRM.dbo.SalesOrderDetailBase 
                  ON HirschInternational_MSCRM.dbo.SalesOrderDetailBase.ProductId = HirschInternational_MSCRM.dbo.ProductBase.ProductId 
                JOIN HirschInternational_MSCRM.dbo.SalesOrderBase 
                  ON HirschInternational_MSCRM.dbo.SalesOrderBase.SalesOrderId = HirschInternational_MSCRM.dbo.SalesOrderDetailBase.SalesOrderId 
Where HirschInternational_MSCRM.dbo.SalesOrderBase.SalesOrderId= //SalesOrderId that I get in main query)

我如何在此查询中传递SalesOrderId