如何获取每个分区结果集
的唯一组号(排名)e.g。我需要如下结果,特别是组列。
column1 column2 column3 column4 row_num group
abc pqr austria type1 1 1
abc pqr austria type1 2 1
abc pqr austria type2 1 2
abc pqr austria type2 2 2
xyz ppp austria type1 1 3
xyz ppp austria type1 2 3
xyz ppp austria type2 1 4
xyz ppp austria type2 2 4
使用SQL ROW_NUMBER
函数,我可以在上表中获得row_num
列。
我尝试使用DENSE_RANK
获取group
列,但结果为
column1 column2 column3 column4 row_num group
abc pqr austria type1 1 1
abc pqr austria type1 2 1
abc pqr austria type2 1 2
abc pqr austria type2 2 2
xyz ppp austria type1 1 1
xyz ppp austria type1 2 1
xyz ppp austria type2 1 2
xyz ppp austria type2 2 2
我需要为每个分区结果集提供唯一值,因为我需要根据组值执行一些计算。
有人可以帮助获得独特的团体排名吗?
答案 0 :(得分:1)
您可能正在尝试将DENSE_RANK
分组。您只需要像DENSE_RANK()OVER(ORDER BY column1 column2 column3 column4)
一样订购它们。
完成查询
SELECT column1 column2 column3 column4,
ROW_NUMBER()OVER(PARTITION BY column1 column2 column3 column4 ORDER BY (SELECT 1)) as row_num,
DENSE_RANK()OVER(ORDER BY column1 column2 column3 column4) as [group]
FROM yourtable
答案 1 :(得分:0)
试试这个:
DECLARE @t TABLE(column1 VARCHAR(10), column2 VARCHAR(10), column3 VARCHAR(10), column4 VARCHAR(10))
INSERT INTO @t VALUES
('abc', 'pqr', 'austria', 'type1'),
('abc', 'pqr', 'austria', 'type1'),
('abc', 'pqr', 'austria', 'type2'),
('abc', 'pqr', 'austria', 'type2'),
('xyz', 'ppp', 'austria', 'type1'),
('xyz', 'ppp', 'austria', 'type1'),
('xyz', 'ppp', 'austria', 'type2'),
('xyz', 'ppp', 'austria', 'type2')
SELECT *,
ROW_NUMBER() OVER(PARTITION BY column1, column4 ORDER BY column4) AS rn,
DENSE_RANK() OVER(ORDER BY column2, column3, column4) AS dr
FROM @t
输出:
column1 column2 column3 column4 rn dr
xyz ppp austria type1 1 1
xyz ppp austria type1 2 1
xyz ppp austria type2 1 2
xyz ppp austria type2 2 2
abc pqr austria type1 1 3
abc pqr austria type1 2 3
abc pqr austria type2 1 4
abc pqr austria type2 2 4