我正在嘗試在我的代碼中添加一些內容并更改此表,但我在 SQL 方面有點新手,我正在努力實作精神上的飛躍以找出如何連接一些東西。
我正在嘗試按作業添加磁區以獲取第 1、2、3、4 行...(因此作業 21980 將有 3 行)
然后我想通過 JOB 添加 MAX of ROW NO (所以基本上我想顯示每個作業的最高行。所以作業 21980 有 3 行,我只想顯示值 3)
然后我想說:當行號不是最大行號時,我希望行中的資料對于列為零:PO$$、Wip Total、per pc、Standard Cost、DIFF、% of Profit
生成此資料的當前 SQL:
SELECT [Job #],
,[Date]
,[Variance Amt]
,[Job QTY]
,[OpenQty]
,[Part #]
,[Material]
,[PCS #]
,[Matrl$$]
,[Date Last Issue]
,case when substring([PurchaseOrders],len([PurchaseOrders]),1) = '|' then substring([PurchaseOrders],1,len([PurchaseOrders])-1) else [PurchaseOrders] end [PurchaseOrders]
,[PO$$]
,[Date Last Rcvd]
,[Wip Total]
,[per pc]
,[Standard Cost]
,[DIFF]
,[% of Profit]
FROM [VarianceView]
Order By [Job #]
我有點了解如何開始第 1 步和第 2 步,但這就是我所知道的。
ROW_NUMBER() OVER(PARTITION BY [Job #]
ORDER BY [Job #] DESC) AS 'RN'
,count(*) over(partition by [Job #]) as maxrn
一些樣本資料
我提前感謝所有幫助!
uj5u.com熱心網友回復:
我認為您的難題中缺少的部分是Common Table Expression。您不能參考視窗函式,除非它首先出現在公用表運算式或子查詢中。以下是我將如何解決您的問題。您還希望函式中的order by子句row_number()包含您希望作業記錄排序的方式。例如,您可能希望使用最新[Date Last Issue]的作為磁區中的最后一條記錄或第一條記錄來評估它們。
如果您只想顯示頂部的 Job # 記錄,則需要添加另一個row_number()函式(例如“RowNumberDesc”),但 [Job #] 是按降序排列的。然后你可以在外部查詢中添加 where 子句來限制 where RowNumberDesc = 1。
with cte as (
select
[Job #]
,[Date]
,[Variance Amt]
,[Job QTY]
,[OpenQty]
,[Part #]
,[Material]
,[PCS #]
,[Matrl$$]
,[Date Last Issue]
,case when substring([PurchaseOrders],len([PurchaseOrders]),1) = '|' then substring([PurchaseOrders],1,len([PurchaseOrders])-1) else [PurchaseOrders] end [PurchaseOrders]
,[PO$$]
,[Date Last Rcvd]
,[Wip Total]
,[per pc]
,[Standard Cost]
,[DIFF]
,[% of Profit]
,ROW_NUMBER() OVER(PARTITION BY [Job #] ORDER BY [Date Last Issue]) AS 'RN'
,count(*) over(partition by [Job #]) as maxrn
FROM [VarianceView]
)
SELECT [Job #]
,[Date]
,[Variance Amt]
,[Job QTY]
,[OpenQty]
,[Part #]
,[Material]
,[PCS #]
,[Matrl$$]
,[Date Last Issue]
,case when substring([PurchaseOrders],len([PurchaseOrders]),1) = '|' then substring([PurchaseOrders],1,len([PurchaseOrders])-1) else [PurchaseOrders] end [PurchaseOrders]
,case when rn <> maxrn then 0 else [PO$$] end as [PO$$]
,[Date Last Rcvd]
,case when rn <> maxrn then 0 else [Wip Total] end as [Wip Total]
,case when rn <> maxrn then 0 else [per pc] end as [per pc]
,case when rn <> maxrn then 0 else [Standard Cost] end as [Standard Cost]
,case when rn <> maxrn then 0 else [DIFF] end as [DIFF]
,case when rn <> maxrn then 0 else [% of Profit] end as [% of Profit]
,rn as [ROW NO by JOB]
,maxrn as [MAX of ROW NO by JOB]
FROM cte
Order By [Job #]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/460696.html
