2

我想添加一個包含每個組中前一行的ID的列。添加包含每個組中前一行的ID的列

樣品:

Product  ID 
Orange  1 
Orange  2 
Orange  3 
Orange  4 
Apple   5 
Apple   6 
Apple   7 
Grapes  8 
Grapes  9 

所需的輸出:

Product  ID 
Orange  1 
Orange  1 
Orange  2 
Orange  3 
Apple   5 
Apple   5 
Apple   6 
Grapes  8 
Grapes  8 

謝謝!

+0

我也想要。你試過什麼了? – lad2025

+0

我使用了MIN([Id)OVER(PARTITION BY Description)),但這只是獲取每個組中的第一行。 – ohhzumm

+0

由於LAG在提及的版本中不可用,因此您必須找到解決方法。提示:以前的ID是所有較小ID的最高ID。如果ID沒有間隔,那麼你甚至可以從每個ID中減去一個,除了每個產品的最小ID之外。 –

回答

0

如果正確地理解你的問題,你可以嘗試這樣的:

SELECT DISTINCT Product, 
       MIN(Id) OVER (PARTITION BY Product) Id 
FROM #Products 

UNION ALL 

SELECT Product, Id 
FROM (
    SELECT Product, 
      Id, 
      ROW_NUMBER() OVER (PARTITION BY Product ORDER BY ID DESC) AS rn 
FROM #Products 
)x 
WHERE rn <> 1 
ORDER BY Id 

輸出

Product Id 
Orange 1 
Orange 1 
Orange 2 
Orange 3 
Apple 5 
Apple 5 
Apple 6 
Grapes 8 
Grapes 8 
+0

它是給重複和計數增加 – mohan111

+0

@Jonathan更新的答案。 –

0

我會用這個或outer apply相關子查詢的辦法。通常情況下,沒有以前的ID,NULL是完全可以接受的:

select s.*, s2.id as previd 
from sample s outer apply 
    (select top 1 s2.id 
     from sample s2 
     where s2.product = s.product and s2.id < s.id 
     order by s2.id desc 
    ) s2 ; 

你似乎想在這種情況下,第一id。這裏是一個一個的解決辦法:

select s.*, coalesce(s2.id, smin.minid) as previd 
from sample s outer apply 
    (select top 1 s2.id 
     from sample s2 
     where s2.product = s.product and s2.id < s.id 
     order by s2.id desc 
    ) s2 outer apply 
    (select min(s2.id) as minid 
     from sample s2 
     where s2.product = s.product 
    ) mins; 

當然,在SQL Server 2012+,您將使用ANSI標準的功能lag()

select s.*, 
     coalesce(lag(s.id) over (partition by s.product order by s.id), 
       min(s.id) over (partition by s.product) 
       ) as sprev 
from sample s; 
0
DECLARE @DUMMY TABLE 
    (
    Product VARCHAR(6) , 
    ID INT 
); 

INSERT INTO @DUMMY (Product, ID) 
VALUES ('Orange', 1), 
     ('Orange', 2), 
     ('Orange', 3), 
     ('Orange', 4), 
     ('Apple', 5), 
     ('Apple', 6), 
     ('Apple', 7), 
     ('Grapes', 8), 
     ('Grapes', 9); 


WITH dummy 
     AS (
      SELECT [Product], [ID], 
        ROW_NUMBER() OVER (PARTITION BY Product ORDER BY ID) AS rn 
      FROM @DUMMY AS [d] 
      ) 
    SELECT [d1].[Product], [d1].[ID], [d2].[ID] 
    FROM dummy AS [d1] 
    LEFT JOIN dummy AS [d2] ON [d2].[Product] = [d1].[Product] AND 
          [d2].[rn] + 1 = [d1].[rn] 
    ORDER BY d1.[ID]; 

PS:如果是2012或更高版本,然後它像PostgreSQL一樣支持ROWS/RANGE。 PS2:您可以使用SQLFiddle將示例數據作爲代碼而不是純文本。

相關問題