任何人都可以帮我一个select语句,它会返回我在下面显示的“Section”编号吗?我发现了一些类似的问题和答案,但没有解决我的具体要求。
我的数据(本例简化)是“序列”和“数据”列,我想根据以下内容生成“部分”列:
答案 0 :(得分:2)
我们可以在这里使用行号方法的差异:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"name": "Test Drive for data ",
"time": "2018-04-03T01:48:51Z",
"coordTimes": [//ARRAY OF DATETIMES] },
"geometry": {
"type": "LineString",
"coordinates": [ //ARRAY OF X, Y, and ELEVATION COORDINATES]
]
}
}
]
}
很难用语言解释为什么这种方法在这里工作,但如果你很好奇,你可以尝试WITH cte AS (
SELECT *,
ROW_NUMBER() OVER (ORDER BY Sequence) -
ROW_NUMBER() OVER (PARTITION BY Data ORDER BY Sequence) rn
FROM yourTable
)
SELECT Sequence, Data, DENSE_RANK() OVER (ORDER BY rn) AS Section
FROM cte
ORDER BY Sequence;
看看发生了什么。
答案 1 :(得分:1)
此解决方案使用窗口函数两次。
-- [2] then use dense_rank() on the smallest sequence by Data
select *, dense_rank() over(order by s)
from
(
-- [1] find the smallest Sequence for each group of Data
select *, s = min(Sequence) over (partition by Data)
from tbl
) t
order by Sequence