如果你是SQL Server 2012中您可以使用LAG與以前行比較值。我使用它來比較數值與上一行 - 我比較SalesOrderID
和PreviousSalesOrderID
- 如果它們不同,請填寫SubTotal
列。
解決方案:
SELECT SalesOrder.SalesOrderID, SalesOrder.SalesOrderNo, t1.PONo,
(CASE
WHEN (t1.PreviousSalesOrderID IS NULL) OR (t1.PreviousSalesOrderID <> SalesOrder.SalesOrderID) THEN SalesOrder.SubTotal
END) as SubTotal
FROM (SELECT SalesOrder.SalesOrderID, PurchaseOrder.PONo,
LAG(SalesOrder.SalesOrderID) OVER (ORDER BY SalesOrder.SalesOrderID) AS PreviousSalesOrderID
FROM SalesOrder LEFT OUTER JOIN PurchaseOrder ON SalesOrder.SalesOrderID = PurchaseOrder.SalesOrderID) AS t1
LEFT OUTER JOIN SalesOrder ON SalesOrder.SalesOrderID = t1.SalesOrderID
輸出(與你的預期輸出):
SalesOrderID SalesOrderNo PONo SubTotal
8 S00008 p7 1544
9 S00009 p8 1644
9 S00009 p262 NULL
10 S00010 p263 4922
10 S00010 p9 NULL
11 S00011 p10 7805
可以共享的表結構(主要是主鍵和外鍵) – Ravi
顯示你現在得到和 –