以下是我的数据:
| col1 | col2 | denserank | whatiwant |
|------|------|-----------|-----------|
| 1 | 1 | 1 | 1 |
| 2 | 1 | 1 | 1 |
| 3 | 2 | 2 | 2 |
| 4 | 2 | 2 | 2 |
| 5 | 1 | 1 | 3 |
| 6 | 2 | 2 | 4 |
| 7 | 2 | 2 | 4 |
| 8 | 3 | 3 | 5 |
这是我到目前为止的查询:
SELECT col1, col2, DENSE_RANK() OVER (ORDER BY COL2) AS [denserank]
FROM [table1]
ORDER BY [col1] asc
我想要实现的是每次col2值发生变化时,我的密集列都会增量(即使值本身被重用)。我实际上无法通过我密集的列来命令,所以这不起作用)。有关示例,请参阅whatiwant
列。
有没有办法用DENSE_RANK()
实现这一目标?还是有替代方案吗?
答案 0 :(得分:4)
我会用这样的递归cte来做:
declare @Dept table (col1 integer, col2 integer)
insert into @Dept values(1, 1),(2, 1),(3, 2),(4, 2),(5, 1),(6, 2),(7, 2),(8, 3)
;with a as (
select col1, col2,
ROW_NUMBER() over (order by col1) as rn
from @Dept),
s as
(select col1, col2, rn, 1 as dr from a where rn=1
union all
select a.col1, a.col2, a.rn, case when a.col2=s.col2 then s.dr else s.dr+1 end as dr
from a inner join s on a.rn=s.rn+1)
col1, col2, dr from s
result:
col1 col2 dr
----------- ----------- -----------
1 1 1
2 1 1
3 2 2
4 2 2
5 1 3
6 2 4
7 2 4
8 3 5
仅在您的col1值不是连续的情况下才需要ROW_NUMBER。如果他们是你可以直接使用递归cte
答案 1 :(得分:3)
使用窗口函数尝试:
with t(col1 ,col2) as (
select 1 , 1 union all
select 2 , 1 union all
select 3 , 2 union all
select 4 , 2 union all
select 5 , 1 union all
select 6 , 2 union all
select 7 , 2 union all
select 8 , 3
)
select t.col1,
t.col2,
sum(x) over (
order by col1
) whatyouwant
from (
select t.*,
case
when col2 = lag(col2) over (
order by col1
)
then 0
else 1
end x
from t
) t
order by col1;
产地:
它执行单个表读取并以col1的递增顺序形成连续相等col2值的组,然后在其上找到密集等级。
x
:如果上一行的col2与此行的col2相同(按增加col1
的顺序排列),则分配值0否则为1 whatyouwant
:通过对最后一步中生成的值col2
的增量总和以及&#,按照增加col1
的顺序创建相等值x
的组39;是你的输出。答案 2 :(得分:3)
以下是使用SUM OVER(Order by)
窗口聚合函数
SELECT col1,Col2,
Sum(CASE WHEN a.prev_val = a.col2 THEN 0 ELSE 1 END) OVER(ORDER BY col1) AS whatiwant
FROM (SELECT col1,
col2,
Lag(col2, 1)OVER(ORDER BY col1) AS prev_val
FROM Yourtable) a
ORDER BY col1;
工作原理:
LAG
窗口函数用于查找col2
col1
仅当前一个SUM OVER(Order by)
不等于当前col2
时, col2
才会增加该数字
答案 3 :(得分:1)
我认为这在纯SQL中可能会使用一些间隙和孤岛技巧,但阻力最小的路径可能是使用会话变量与LAG()
结合来跟踪计算的密集等级何时更改值。在下面的查询中,我使用@a
来跟踪密集排名的变化,当它发生变化时,此变量会增加1。
DECLARE @a int
SET @a = 1
SELECT t.col1,
t.col2,
t.denserank,
@a = CASE WHEN LAG(t.denserank, 1, 1) OVER (ORDER BY t.col1) = t.denserank
THEN @a
ELSE @a+1 END AS [whatiwant]
FROM
(
SELECT col1, col2, DENSE_RANK() OVER (ORDER BY COL2) AS [denserank]
FROM [table1]
) t
ORDER BY t.col1