2016-04-08 51 views
-2

我有以下查詢:與一列只在一個相同的ID返回數據的多行如果行的sql 2

SELECT dbo.SalesOrder.SalesOrderID, dbo.SalesOrder.SalesOrderNo, dbo.SalesOrder.SubTotal, dbo.PO.PONo 
FROM dbo.SalesOrder 
LEFT OUTER JOIN dbo.PO ON dbo.SalesOrder.SalesOrderID = dbo.PO.SalesOrderID 

這顯示的銷售訂單,其小計和連接寶的名單。當有多個po連接到相同的銷售訂單時,它將返回每個po行的小計。我希望它只在該銷售訂單的第一行顯示小計。

example data

+0

可以共享的表結構(主要是主鍵和外鍵) – Ravi

+0

顯示你現在得到和 –

回答

0

如果你是SQL Server 2012中您可以使用LAG與以前行比較值。我使用它來比較數值與上一行 - 我比較SalesOrderIDPreviousSalesOrderID - 如果它們不同,請填寫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 
+0

GROUP BY儘管將整行分組,但我希望將每行分開,但僅在該ID的第一行顯示小計行 – khenry

+0

我只有SQL Server 2008,有沒有相當於2008年? – khenry

+0

有可能:[用於SQL Server 2008的LAG和LEAD](https://sqlscope.wordpress.com/2014/05/26/lag-and-lead-for-sql-server-2008/) – Antony

相關問題