列值更改时排序Sql Server表行

时间:2017-06-11 05:42:22

标签: sql sql-server rank

我在SQL Server中有一个像这样的表 -

ID  Employee_id  group_field_code   from_date              To_date
================================================================================
1   44855           055            2015-04-01 00:00:00  2015-04-02 17:37:26
2   44855           055            2015-04-02 17:37:27  2015-04-25 09:31:10
3   44855           055            2015-04-25 09:31:11  2015-09-18 14:58:59
4   44855           053            2015-09-18 15:00:00  2016-04-02 02:58:59
5   44855           055            2016-04-02 03:00:00  2016-05-26 02:58:59
6   44855           055            2016-05-25 13:25:23  2016-09-07 14:58:59
7   44855           055            2016-05-26 03:00:00  2016-05-25 13:25:22
8   44855           052            2016-09-07 15:00:00  2017-05-22 02:58:59
9   44855           055            2017-05-22 03:00:00  NULL

当组字段发生变化时,我想要的是一行的新排名。喜欢 - 对于ID 1-3(group_code 55)我想要一个Rank,对于ID 4(group_Code更改,53)我想要另一个等级,然后再次为ID 5(group_code 5重新到达)我想要另一个等级,依此类推。这可能在SQL Server中使用Rank或其他功能吗?

2 个答案:

答案 0 :(得分:2)

我们可以尝试使用行号方法的区别:

SELECT
    ID, Employee_id, group_field_code, from_date, To_date,
    DENSE_RANK() OVER (ORDER BY rank) rank
FROM
(
    SELECT *,
        ROW_NUMBER() OVER (ORDER BY from_date) -
        ROW_NUMBER() OVER (PARTITION BY group_field_code ORDER BY from_date) AS rank
    FROM yourTable
) t
ORDER BY t.from_date;

在这里演示:

Rextester

答案 1 :(得分:2)

`SELECT dt.*,
       sum(dt.rnk) over (
                         ORDER BY dt.id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS final_rnk
FROM
  (SELECT e2.*,
          CASE
          WHEN e1.group_field_code <> e2.group_field_code THEN 1
          ELSE 0
      END AS rnk
   FROM employee e1
   INNER JOIN employee e2 ON e1.id = e2.id-1) dt ;`

result