我有一张用户ID和值表。我想为每个用户选择最常出现的值。
这是表格的样子......
UserID | Value
--------------------
501 | 1
501 | 1
24 | 2
55 | 1
55 | 1
55 | 3
所以我希望我的查询输出表看起来像......
UserID | Value
--------------------
501 | 1
24 | 2
55 | 1
答案 0 :(得分:1)
一种方法是使用count
和row_number
窗口函数,如下所示:
select UserID, Value from (
select t.*, row_number() over(partition by UserID order by cnt desc) as rn from (
select your_table.*, count(*) over(partition by UserID, Value) as cnt from your_table
) t
) tt
where rn = 1
答案 1 :(得分:0)
您需要group by
和count()
喜欢
select UserID, count(`Value`) as `value`
from tbl1
group by UserID
order by count(`Value`) desc
答案 2 :(得分:0)
我认为你的例子中用户55的最高值是3对吗?
a(href='/', class="link", class={"-active": page === 'home'}) Home page
编辑:拉胡尔说的话。
答案 3 :(得分:0)
SELECT DISTINCT ON(id)
id,
value
FROM
(
SELECT
id,
value,
count(value) AS cnt
FROM
tbl
GROUP BY id, value
) mq
ORDER BY id, cnt DESC