本文介绍了更改编号列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 NAME 和 PAY,但在这个例子中我需要 CHANGEGROUP:
I have NAME and PAY, but I need CHANGEGROUP in this example:
NAME PAY DATE CHANGEGROUP
Sally 12 10/01/2011 1
Sally 12 10/01/2011 1
Sally 12 11/02/2011 1
Sally 12 11/02/2011 1
Sally 12 12/01/2012 1
Sally 13 04/23/2013 2
Sally 12 04/24/2013 3
Sally 10 05/01/2013 4
Sally 10 10/01/2014 4
我尝试了 RANK()
和 DENSE_RANK()
,但它们是根据价值分组的——因为工资下降了,我的分组混乱了.我看到了 this 但它不是与旧版本的 SQL 2005 兼容
I tried RANK()
and DENSE_RANK()
, but they group according to the value - because pay goes down, it messes up my grouping. I saw this but it's not compatible with this older version of SQL 2005
推荐答案
这是一个差距和孤岛问题.
This is a gaps and islands problem.
一种方法.SQL 小提琴
WITH T1
AS (SELECT *,
ROW_NUMBER()
OVER (
PARTITION BY NAME
ORDER BY DATE) - ROW_NUMBER()
OVER (
PARTITION BY NAME, [PAY]
ORDER BY DATE) AS Grp
FROM Table1),
T2
AS (SELECT *,
MIN(DATE)
OVER (
PARTITION BY NAME, Grp) AS MinDate
FROM T1)
SELECT [NAME],
[PAY],
[DATE],
DENSE_RANK()
OVER (
PARTITION BY NAME
ORDER BY MinDate) AS CHANGEGROUP
FROM T2
ORDER BY NAME,
MinDate
这篇关于更改编号列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!