在SQL中使用rank()

时间:2019-04-03 18:05:27

标签: sql sql-server

以下查询为我提供了整天的repeated值。如何找到repeated列中实际上重复的前3个repeated值。

注意
我不需要top 3列中的repeated值。我想在repeated列中看到前3个重复的值。

select days, count(*) as repeated from 
(
select 
datediff(day, EnrollDate, InsertDate) as days
from 
(
select 
m.id as memberid,
min(m.EnrollDate) as enrolldate, min(fc.InsertDate) as insertdate
from membersinclude m
join case fc
on m.id = fc.MemberId
and CancelDate < '2019-01-01 00:00:00.000'
and EnrollDate > '2015-01-01 00:00:00.000'
group by m.id
) a
) b
group by days

更新

days    mode
19      11
0       10
211     10
42      10
34      10
29      10
35      9
183     9
49      9

如果这是上面查询的输出,我希望它按此顺序返回10, 9, 11,因为10的结果比9的结果多,而11的结果比{{1} }

2 个答案:

答案 0 :(得分:0)

使用JsonArray jsonObject = new JsonParser() .parse(result) .getAsJsonArray(); List<String> names = new ArrayList<>(); for (JsonElement jsonElement : jsonObject) { names.add(jsonElement.getAsJsonObject().get("properties").getAsString()); 关键字

top

答案 1 :(得分:0)

;WITH cte AS (
    select 
    m.id as memberid,
    DATEDIFF(DAY, MIN(m.EnrollDate), MIN(fc.InsertDate)) AS days
    from membersinclude m
    join [case] fc
    on m.id = fc.MemberId
    and CancelDate < '2019-01-01 00:00:00.000'
    and EnrollDate > '2015-01-01 00:00:00.000'
    group by m.id
),
cte_grouped AS (
    SELECT days, COUNT(*) AS cnt
    FROM cte
    GROUP BY days
),
cte_ranked AS (
    SELECT days, RANK() OVER (ORDER BY cnt desc) rnk
    FROM cte_grouped
)
SELECT TOP(3) days
FROM cte_ranked
ORDER BY rnk

使用此示例数据:

CREATE TABLE membersinclude (id INT, enrolldate DATE, canceldate DATE)
CREATE TABLE [case] (memberid INT, insertdate DATE)

INSERT INTO membersinclude VALUES (1, '1/1/2016', '1/1/2018')
INSERT INTO membersinclude VALUES (2, '1/1/2016', '1/1/2018')
INSERT INTO membersinclude VALUES (3, '1/1/2016', '1/1/2018')
INSERT INTO membersinclude VALUES (4, '1/1/2016', '1/1/2018')
INSERT INTO membersinclude VALUES (5, '1/1/2016', '1/1/2018')
INSERT INTO membersinclude VALUES (6, '1/1/2016', '1/1/2018')
INSERT INTO membersinclude VALUES (7, '1/1/2016', '1/1/2018')
INSERT INTO membersinclude VALUES (8, '1/1/2016', '1/1/2018')
INSERT INTO membersinclude VALUES (9, '1/1/2016', '1/1/2018')
INSERT INTO membersinclude VALUES (10, '1/1/2016', '1/1/2018')

INSERT INTO [CASE] VALUES (1, '2/1/2016')
INSERT INTO [CASE] VALUES (2, '2/1/2016')
INSERT INTO [CASE] VALUES (3, '2/1/2016')
INSERT INTO [CASE] VALUES (4, '2/1/2016')
INSERT INTO [CASE] VALUES (5, '3/1/2016')
INSERT INTO [CASE] VALUES (6, '3/1/2016')
INSERT INTO [CASE] VALUES (7, '3/1/2016')
INSERT INTO [CASE] VALUES (8, '4/1/2016')
INSERT INTO [CASE] VALUES (9, '4/1/2016')
INSERT INTO [CASE] VALUES (10, '5/1/2016')

将其分组为cte_grouped:

days    cnt
31      4
60      3
91      2
121     1

然后返回由cnt desc排名的前3名:

days
31
60
91