我有以下查询:
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行的小计。我希望它只显示该销售订单第一行的小计。
答案 0 :(得分:0)
如果您使用的是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