我正在尝试根据前几行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
谢谢