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将示例数据作为代码而不是纯文本。

相关问题