使用 group by 打印 table 中的最大值
Printing the highest value in a table using group by
首先,对于令人困惑的标题感到抱歉,我不知道如何更好地描述它,它很复杂。
我有一个 table 看起来像这样:
send_org
rec_org
partecipants
a
b
1
a
c
2
b
d
2
b
c
3
b
f
3
等等。
对于每个 send,我要打印的是具有最高 partecipants 数量的行(我不关心重复项,我只需要数字最高的一行);所以,在这种情况下,我期待
a c 2
b c 3
使用 MySQL,我的查询将是
SELECT send_org, receive_org, partecipants
FROM (
SELECT *
FROM tab
ORDER BY partecipants DESC) p
GROUP BY send_org;
而且有效。
Hive 给我关于不在 GROUP BY 语句中的键的错误,所以我尝试切换到 collection_set(),像这样
SELECT send_org, collect_set(receive_org)[0], max(partecipants) partecipants
FROM tab
GROUP BY send_org
ORDER BY partecipants;
但是collection_set()[0]returns列中的第一个值rec(正确分组),不是相关的值参加人数.
你有什么建议吗?
如果您需要更好地查看 SQL 版本,它是 here。
您可以使用row_number
来确定“参与者人数最多的行” 例如
SELECT send_org, receive_org, partecipants
FROM (
SELECT
*,
ROW_NUMBER() OVER (
PARTITION BY send_org
ORDER BY partecipants DESC
) rn
FROM tab
) p
where rn=1
首先,对于令人困惑的标题感到抱歉,我不知道如何更好地描述它,它很复杂。
我有一个 table 看起来像这样:
send_org | rec_org | partecipants |
---|---|---|
a | b | 1 |
a | c | 2 |
b | d | 2 |
b | c | 3 |
b | f | 3 |
等等。
对于每个 send,我要打印的是具有最高 partecipants 数量的行(我不关心重复项,我只需要数字最高的一行);所以,在这种情况下,我期待
a c 2
b c 3
使用 MySQL,我的查询将是
SELECT send_org, receive_org, partecipants
FROM (
SELECT *
FROM tab
ORDER BY partecipants DESC) p
GROUP BY send_org;
而且有效。
Hive 给我关于不在 GROUP BY 语句中的键的错误,所以我尝试切换到 collection_set(),像这样
SELECT send_org, collect_set(receive_org)[0], max(partecipants) partecipants
FROM tab
GROUP BY send_org
ORDER BY partecipants;
但是collection_set()[0]returns列中的第一个值rec(正确分组),不是相关的值参加人数.
你有什么建议吗?
如果您需要更好地查看 SQL 版本,它是 here。
您可以使用row_number
来确定“参与者人数最多的行” 例如
SELECT send_org, receive_org, partecipants
FROM (
SELECT
*,
ROW_NUMBER() OVER (
PARTITION BY send_org
ORDER BY partecipants DESC
) rn
FROM tab
) p
where rn=1