SQL按时间间隔对数据分组

时间:2018-06-19 19:45:26

标签: tsql rank

全部

我正在寻找一种可扩展的方法,以将这些员工ID“存储”为“左”或“右”维,以进行报告。我需要将前3个不同的ID分组到左组,然后将下3个分组到右组,依此类推,再将3个分组到左组,依此类推。实际的数据集包含数百个ID。

谢谢

原始数据:

Rank    Faculty_Staff_ID
----------------------------
1       zcrm_315216
1       zcrm_315216
1       zcrm_315216
2       zcrm_315217
2       zcrm_315217
2       zcrm_315217
3       zcrm_315218
4       zcrm_315219
4       zcrm_315219
4       zcrm_315219
5       zcrm_319795
5       zcrm_319795
6       zcrm_315220
6       zcrm_315220
7       zcrm_315221
8       zcrm_315222
9       zcrm_315223
9       zcrm_315223
9       zcrm_315223

所需的输出:

L_or_R    Rank    Faculty_Staff_ID
----------------------------------
L         1       zcrm_315216
L         1       zcrm_315216
L         1       zcrm_315216
L         2       zcrm_315217
L         2       zcrm_315217
L         2       zcrm_315217
L         3       zcrm_315218
R         4       zcrm_315219
R         4       zcrm_315219
R         4       zcrm_315219
R         5       zcrm_319795
R         5       zcrm_319795
R         6       zcrm_315220
R         6       zcrm_315220
L         7       zcrm_315221
L         8       zcrm_315222
L         9       zcrm_315223
L         9       zcrm_315223
L         9       zcrm_315223

2 个答案:

答案 0 :(得分:2)

您可以关注

  1. RowNumber列号上输入Rank

  2. 在子查询上使用Rank使3CASE WHEN分组。

  3. 在主查询CASE WHEN上使用grp % 2 = 0拆分LR

您可以尝试此查询。

SELECT t.*,(CASE WHEN grp % 2 = 0 then 'R' ELSE 'L' END) 'L_or_R'
FROM T t
INNER JOIN (
    SELECT rnk,SUM(CASE WHEN (rn -1)% 3 = 0 THEN 1 ELSE 0 END) OVER(ORDER BY rn) grp
    FROM (
       SELECT rnk,ROW_NUMBER() OVER(ORDER BY rnk) rn 
       FROM 
       (
          SELECT DISTINCT Rank rnk
          FROM T
        )t
    ) t
) t1 on t.Rank = t1.rnk

sqlfiddle:https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=615c015a856b57511a2dcf0323f0d4a5

答案 1 :(得分:0)

要解决此问题,需要使用DENSE_RANK函数和一些算术功能。

CREATE TABLE T(
    Rank INT,
    Faculty_Staff_ID VARCHAR(50)
);

INSERT INTO T VALUES
  (1,'zcrm_315216'),
  (1,'zcrm_315216'),
  (1,'zcrm_315216'),
  (2,'zcrm_315217'),
  (2,'zcrm_315217'),
  (2,'zcrm_315217'),
  (2,'zcrm_315217'),
  (2,'zcrm_315217'),
  (2,'zcrm_315217'),
  (2,'zcrm_315217'),
  (2,'zcrm_315217'),
  (2,'zcrm_315217'),
  (2,'zcrm_315217'),
  (2,'zcrm_315217'),
  (2,'zcrm_315217'),
  (2,'zcrm_315217'),
  (2,'zcrm_315217'),
  (2,'zcrm_315217'),
  (2,'zcrm_315217'),
  (2,'zcrm_315217'),
  (2,'zcrm_315217'),
  (3,'zcrm_315218'),
  (4,'zcrm_315219'),
  (4,'zcrm_315219'),
  (4,'zcrm_315219'),
  (5,'zcrm_319795'),
  (5,'zcrm_319795'),
  (6,'zcrm_315220'),
  (6,'zcrm_315220'),
  (7,'zcrm_315221'),
  (8,'zcrm_315222'),
  (10,'zcrm_315223'),
  (21,'zcrm_315223'),
  (23,'zcrm_315223'),
  (25,'zcrm_315223'),
  (25,'zcrm_315223'),
  (27,'zcrm_315223');

SELECT *,
  IIF(((DENSE_RANK() OVER (ORDER BY Rank) - 1) / 3) % 2 = 0, 'L', 'R') L_or_R
FROM T
ORDER BY Rank;

欢迎here进行检查。