如何在 sql 上 select 直方图?
How to select histogram-like on sql?
我有以下 table messages
:
destination_number | message_text | pk/sender_number/metadata/timestamps/other_stuff
123 | hi | ...
456 | at 4 | ...
123 | how are you? | ...
123 | I'm David | ...
456 | please | ...
789 | no | ...
789 | stop | ...
012 | exit | ...
做 select count(1) as quantity, destination_number from messages group by destination_number
我得到:
quantity | destination_number
3 | 123
2 | 456
2 | 789
1 | 012
现在我想要一个直方图:
quantity | quantity_of_numbers_that_received_that_quantity
3 | 1 // only number 123 received 3 messages
2 | 2 // numbers 456 and 789 received 2 messages
1 | 1 // only 012 received 1 message
我的问题是:什么查询会直接从 messages
带来最后一个 table?
select quantity, count(destination_number) as quantity_of_numbers_that_received_that_quantity
from (
select count(1) as quantity, destination_number
from messages
group by destination_number
)
group by quantity
如果我没理解错,请使用二级聚合:
select quantity, count(*)
from (select count(1) as quantity, destination_number
from messages
group by destination_number
) m
group by quantity
order by quantity;
我通常会包含类似 min(destination_number), max(destination_number)
的内容来查看示例值。
我有以下 table messages
:
destination_number | message_text | pk/sender_number/metadata/timestamps/other_stuff
123 | hi | ...
456 | at 4 | ...
123 | how are you? | ...
123 | I'm David | ...
456 | please | ...
789 | no | ...
789 | stop | ...
012 | exit | ...
做 select count(1) as quantity, destination_number from messages group by destination_number
我得到:
quantity | destination_number
3 | 123
2 | 456
2 | 789
1 | 012
现在我想要一个直方图:
quantity | quantity_of_numbers_that_received_that_quantity
3 | 1 // only number 123 received 3 messages
2 | 2 // numbers 456 and 789 received 2 messages
1 | 1 // only 012 received 1 message
我的问题是:什么查询会直接从 messages
带来最后一个 table?
select quantity, count(destination_number) as quantity_of_numbers_that_received_that_quantity
from (
select count(1) as quantity, destination_number
from messages
group by destination_number
)
group by quantity
如果我没理解错,请使用二级聚合:
select quantity, count(*)
from (select count(1) as quantity, destination_number
from messages
group by destination_number
) m
group by quantity
order by quantity;
我通常会包含类似 min(destination_number), max(destination_number)
的内容来查看示例值。