或者您可以嘗試使用row_number(),正如Gordon Linoff從之前的答案中所建議的那樣確定第一次銷售。
數據:使用CTE和ROW_NUMBER
IF (OBJECT_ID('tempdb..#TmpData') IS NOT NULL)
BEGIN
DROP TABLE #TmpData
END
CREATE TABLE #TmpData (dataid INT, cost MONEY,)
CREATE CLUSTERED INDEX IX_TmpData_dataid ON #TmpData (dataid)
INSERT INTO #TmpData
(dataid, cost)
VALUES (1, 1),
(2, 2)
IF (OBJECT_ID('tempdb..#TmpSale') IS NOT NULL)
BEGIN
DROP TABLE #TmpSale
END
CREATE TABLE #TmpSale
(
saleid INT ,
dataid INT ,
price MONEY
)
CREATE CLUSTERED INDEX IX_TmpSale ON #TmpSale (saleid)
CREATE NONCLUSTERED INDEX IX_TmpSale_dataid ON #TmpSale (dataid)
INSERT INTO #TmpSale
(saleid, dataid, price)
VALUES (1, 1, 5),
(2, 2, 3),
(3, 2, 4)
:
;WITH PROFIT
AS (SELECT d.dataid d_dataid ,
d.cost ,
s.saleid ,
s.dataid s_dataid ,
price ,
ROW_NUMBER() OVER (PARTITION BY d.dataid ORDER BY s.saleid) ctr
FROM #TmpData D
JOIN #TmpSale S ON S.dataid = D.dataid
)
SELECT saleid ,
d_dataid dataid ,
price ,
IIF(ctr = 1, cost, 0) cost ,
IIF(ctr = 1, (price - cost), price) profit
FROM PROFIT
OPTION (MAXRECURSION 32767)
結果:
saleid dataid price cost profit
----------- ----------- ------- ------- --------
1 1 5.00 1.00 4.00
2 2 3.00 2.00 1.00
3 2 4.00 0.00 4.00
你是什麼意思, 「第一」?在升序saleid? SQL表沒有順序。您是否對有序SQL結果集(查詢結果)進行了說明?它的排序來源是什麼? – philipxy