0

我正在尝试根据前几行ROW_NUMBER()与当前行相比计算位置变化ROW_NUMBER()

我的查询使用带有 ROW_NUMBER() OVER .. 子句的递归 cte,该子句巧妙地为我提供了按年份划分的结果行号。

WITH positions AS (
    SELECT 
        [incidents].state_id, [incidents].year_id, MAX(number_of_incidents) AS total_incidents_in_year,
        ROW_NUMBER() OVER(PARTITION BY [incidents].year_id ORDER BY MAX(number_of_incidents) DESC) AS position
    FROM
        [incidents]
    INNER JOIN
        years AS dy ON dy.year_id = [incidents].year_id
    INNER JOIN
        states AS ds on ds.state_id = [incidents].state_id
    GROUP BY
        [incidents].state_id, [incidents].year_id
)

在此之后,我的查询然后比较位置以计算行号之间的变化。

SELECT
    ds.state_name, ds.state_id, [before].total_incidents_in_year, dy.year,
    [before].position AS before_position, [after].position AS after_position,
    ([before].position - [after].position) AS change
FROM
    positions AS [before]
LEFT JOIN 
    positions AS [after] ON [before].position = [after].position + 1 AND [before].state_id = [after].state_id AND [before].year_id = [after].year_id
INNER JOIN
    years AS dy ON dy.year_id = [before].year_id
INNER JOIN
    states AS ds on ds.state_id = [before].state_id
ORDER BY
    [before].year_id ASC, [before].total_incidents_in_year DESC

不幸的是,这不起作用,因为 [after] 位置始终为空。

这有点难以解释,所以我提供了一个 sqlfiddle 链接:http ://www.sqlfiddle.com/#!18/c7e57e/1

--

这张图片直观地解释了我想要实现的目标 我设想的输出

2011 年明尼苏达排名第 1,2012 年明尼苏达排名第 3,变化为 +2

2011 年爱荷华州排名第 6,2012 年爱荷华州排名第 4,变化为 -2

2011 年南达科他州排名第 5,2012 年南达科他州排名第 5,变化为 0

谢谢

4

1 回答 1

1

弄清楚了。

我错误地尝试在 ROW_NUMBER() 上加入,这将导致不匹配的加入,因为行号不一定与状态 ID 正确对齐。

在改变它加入之后,year这是计算每年变化的正确方法,所有这些都聚集在一起。

WITH positions AS (
    SELECT 
        [incidents].state_id, dy.year, MAX(number_of_incidents) AS total_incidents_in_year,
        ROW_NUMBER() OVER(PARTITION BY dy.year ORDER BY MAX(number_of_incidents) DESC) AS position
    FROM
        [incidents]
    INNER JOIN
        years AS dy ON dy.year_id = [incidents].year_id
    INNER JOIN
        states AS ds on ds.state_id = [incidents].state_id
    GROUP BY
        [incidents].state_id, dy.year
)
SELECT
    ds.state_name, ds.state_id, [before].total_incidents_in_year, dy.year,
    [before].position AS before_position,
    ([before].position - [after].position) AS change
FROM
    positions AS [before]
LEFT JOIN 
    positions AS [after] ON [before].state_id = [after].state_id AND [before].year = [after].year + 1
INNER JOIN
    years AS dy ON dy.year = [before].year
INNER JOIN
    states AS ds on ds.state_id = [before].state_id
ORDER BY
    [before].year ASC, [before].total_incidents_in_year DESC

http://www.sqlfiddle.com/#!18/c7e57e/11

于 2019-04-25T09:29:34.783 回答