表格中的每一行都指定了购买该产品的产品和国家。像这样:
Product 1, Country A
Product 1, Country B
Product 1, Country C
Product 2, Country A
Product 2, Country B
我想添加另一列,该列基本上统计每个产品的每个国家/地区。每次从一个新产品开始。
Product 1, Country A, Country 1
Product 1, Country B, Country 2
Product 1, Country C, Country 3
Product 2, Country A, Country 1
Product 2, Country B, Country 2
过去,这是通过vba脚本完成的,只需运行一个循环,将产品名称与上一行的产品名称进行比较,如果相同则添加+1,否则将添加1。我想知道是否有一种方法可以通过SQL来实现。
答案 0 :(得分:2)
使用row_number()
select *, row_number() over(partition by product order by country) as rn
from tablename
答案 1 :(得分:1)
CREATE TABLE #Table1
([col1] varchar(9), [col2] varchar(9))
;
INSERT INTO #Table1
([col1], [col2])
VALUES
('Product 1', 'Country A'),
('Product 1', 'Country B'),
('Product 1', 'Country C'),
('Product 2', 'Country A'),
('Product 2', 'Country B')
;
select *, concat('Country',' ',row_number() over(partition by [col1] order by [col1])) as rn_column
from #Table1
输出
col1 col2 rn_column
Product 1 Country A Country1
Product 1 Country B Country2
Product 1 Country C Country3
Product 2 Country A Country1
Product 2 Country B Country2