Sql 在子查询的where中使用主集合的值
我有下面的场景。我有两张桌子需要连接。第一个表是主记录。第二个表是一个多行子记录,需要按降序数据排序,然后只将顶层子记录加入主记录。我唯一能想到的是:Sql 在子查询的where中使用主集合的值,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有下面的场景。我有两张桌子需要连接。第一个表是主记录。第二个表是一个多行子记录,需要按降序数据排序,然后只将顶层子记录加入主记录。我唯一能想到的是: WITH SCD as (select top 100000 Part_Id as PartID, [Date_Created] ,[Production_Part_Status_Id] ,[Operations_Labor_Rollup] ,[Operations_Materials_Rollup]
WITH SCD as (select top 100000 Part_Id as PartID, [Date_Created]
,[Production_Part_Status_Id]
,[Operations_Labor_Rollup]
,[Operations_Materials_Rollup]
,[Purchased_Subpart_Rollup]
,[Production_Subpart_Rollup] from
Production_Part_Supplier_Cost_Detail order by Date_Created desc)
SELECT
pp.Part_Number
,pp.Part_Name
,pp.Revision
,pp.EAU_Quantity
,pp.Drawing_Number
,pp.Net_Weight
,pp.Current_Price_Each
,pp.Buyer_Stock_Id
,pp.Current_Price_Each -
(COALESCE(Operations_Labor_Rollup, 0.0) +
COALESCE(Operations_Materials_Rollup, 0.0) +
COALESCE(Purchased_Subpart_Rollup, 0.0) +
COALESCE(Production_Subpart_Rollup, 0.0)) as [variance]
,case when pp.Current_Price_Each = 0 or pp.Current_Price_Each IS null then 0 else
(COALESCE(Operations_Labor_Rollup, 0.0) +
COALESCE(Operations_Materials_Rollup, 0.0) +
COALESCE(Purchased_Subpart_Rollup, 0.0) +
COALESCE(Production_Subpart_Rollup, 0.0)) / pp.Current_Price_Each end as [Variance Percent]
,pp.Variance * pp.EAU_Quantity as [Annualized Variance]
FROM
Production_Part AS pp
left join (SELECT TOP 1 * FROM SCD where Part_Id = PartID) ppscd on ppscd.PartID = pp.Part_Id
WHERE
pp.Buyer_Id = @buyer_id;
我遇到的问题是子查询中的WHERE不能引用主表的值。如何解决这个问题?当您的限制
顶部和顺序出现在不同的位置时,这可能看起来有效,但实际上失败了。我怀疑您将TOP100000
添加到CTE中是为了“关闭查询优化器”,但实际上您所做的只是隐藏了一个bug
与其使用TOP
和orderby
,我们可以使用行编号()
:
;WITH SCD as (select Part_Id as PartID, [Date_Created]
,[Production_Part_Status_Id]
,[Operations_Labor_Rollup]
,[Operations_Materials_Rollup]
,[Purchased_Subpart_Rollup]
,[Production_Subpart_Rollup]
,ROW_NUMBER() OVER (PARTITION BY Part_ID
ORDER BY Date_Created desc) as rn
from
Production_Part_Supplier_Cost_Detail)
SELECT
pp.Part_Number
,pp.Part_Name
,pp.Revision
,pp.EAU_Quantity
,pp.Drawing_Number
,pp.Net_Weight
,pp.Current_Price_Each
,pp.Buyer_Stock_Id
,pp.Current_Price_Each -
(COALESCE(Operations_Labor_Rollup, 0.0) +
COALESCE(Operations_Materials_Rollup, 0.0) +
COALESCE(Purchased_Subpart_Rollup, 0.0) +
COALESCE(Production_Subpart_Rollup, 0.0)) as [variance]
,case when pp.Current_Price_Each = 0 or pp.Current_Price_Each IS null then 0 else
(COALESCE(Operations_Labor_Rollup, 0.0) +
COALESCE(Operations_Materials_Rollup, 0.0) +
COALESCE(Purchased_Subpart_Rollup, 0.0) +
COALESCE(Production_Subpart_Rollup, 0.0)) / pp.Current_Price_Each end as [Variance Percent]
,pp.Variance * pp.EAU_Quantity as [Annualized Variance]
FROM
Production_Part AS pp
left join SCD ppscd on ppscd.PartID = pp.Part_Id and
ppscd.rn = 1
WHERE
pp.Buyer_Id = @buyer_id;
完美的你刚刚救了我!