我有一個存儲過程,我必須從嵌套的子查詢中檢索一列。我知道如何獲得它,如果它只嵌套一次,但對於我的這種情況,我需要顯示的列是雙重嵌套。如何從左連接中的嵌套子查詢中檢索列?
SELECT a.vendor,
a.last,
MaxInv
FROM
(
SELECT vendor, day
FROM tblvendor) a
LEFT JOIN (SELECT vendor, tblarinv.arinv, tblardetail.arddate
Sum([MaxQty]*[ActualCost]) AS MaxInv,
FROM tblarinv
INNER JOIN tblardetail
ON tblarinv.id= tblardetail.id)
group by a.vendor,a.last
在上面的例子中,我必須從左連接LEFT JOIN (SELECT vendor,tblarinv.arinv, tblardetail.arddate
檢索兩列。最初,select語句中只有供應商,但因爲我需要tblarinv.arinv, tblardetail.arddate
,所以我在左連接中的select語句中添加了它們。然後,當我嘗試在第一個SELECT語句中添加此字段時,它不會識別錯誤提示'多部分標識符無法綁定'。 任何人都可以幫助我嗎?
這裏是我的編輯查詢:
SELECT
a.Vendor,
,CASE WHEN sum(GP)<>0 THEN GP ELSE 0 END GP
,a.ThreeMonths
,CASE WHEN sum(GP)<>0 THEN GP/@WorkDaysElapsed ELSE 0 END AS AvgDailyGP
,CurrentInv
,MaxInv
,Inventory_Variance
FROM
(Select Vendor, sum(GrossProfit) ThreeMonths,
(Select sum(GrossProfit) From dbo.MonthlySales with (nolock) Where EndOfMonth Between dateadd(m,-3,@First) and @First-1) as AllThreeMonths
FROM MonthlySales with (nolock)
Where EndOfMonth>=dateadd(m,-3,@First)
Group By Vendor
Having sum(GrossProfit)<>0) a
LEFT JOIN (Select tblMaterial.Vendor, tblARDetail.ARInvoiceID, tblARDetail.ARInvoiceDetailID, tblARInv.ARInvoiceDate
,(Sum(SplitAmount))-(Sum((CASE WHEN SplitAmount<0 THEN -1*ABS([Quantity]) ELSE ABS([Quantity]) END)*dbo.fn_CalculatePrice_Decimal(tblARDetail.UnitCost,tblARDetail.ProductDiscountPct))) AS GP
FROM tblARInv with (nolock)
INNER JOIN tblARDetail with (nolock) ON tblARDetail.ARInvoiceID = tblARInv.ARInvoiceID
INNER JOIN tblMaterial with (nolock) ON tblMaterial.MaterialID = tblARDetail.MaterialID
INNER JOIN [dbo].[tblCust]
ON [tblCust].[CustomerID] = [tblARInv].[CustomerID]
Where tblARInv.Date>= '' + cast(Month(GetDate()) as varchar(2)) + '/1/' + cast(year(GetDate()) as varchar(4)) + ''
AND [tblCust].[Status] != 8 --Internal
Group By tblMaterial.Vendor, tblARDetail.ARInvoiceID, tblARDetail.ARInvoiceDetailID, tblARInv.ARInvoiceDate)
ThisMonth ON ThisMonth.Vendor=a.Vendor
Group By
a.Vendor
,GP
,a.ThreeMonths
,AllThreeMonths
,CurrentInv
,MaxInv
,Inventory_Variance
END
所以,我需要找回tblARDetail.ARInvoiceID, tblARDetail.ARInvoiceDetailID, tblARInv.ARInvoiceDate
我加在上面編輯查詢。
該查詢看起來不正確的。 'last'從哪裏來?你在'a'的連接和在'left join'後的未命名派生表在哪裏?你爲什麼要在未命名的派生表之外進行聚合而不是在其內部進行聚合?你的派生表中有'vendor'來自哪裏? – SqlZim
這裏是一個開始的好地方。 http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/ –
@SqlZim:我的查詢是複雜,所以我想給簡單的例子。對不起,我會嘗試正確編輯我的代碼。 – toofaced