我使用的是Amazon RDS(Aurora),因此无法访问crosstab()函数。 我的数据集是每个用户的特定操作数,如下所示:
| uid | action1 | action2 |
| alice | 2 | 2 |
| bob | 1 | 2 |
| charlie | 5 | 0 |
如何透过此数据集制作动作计数直方图?所以它看起来像:
# | Action1 | Action2
---------------------
0 | | 1
1 | 1 |
2 | 1 | 2
3 | |
4 | |
5 | 1 |
6 | |
这是我已经使用已输入值的SQL小提琴:http://sqlfiddle.com/#!17/2b966/1
答案 0 :(得分:0)
我有一个解决方案,但它非常详细:
WITH nums AS (
SELECT n
FROM (VALUES (0), (1), (2), (3), (4), (5)) nums(n)
),
action1_counts as (
select
action1,
count(*) as total
from test
group by 1
),
action2_counts as (
select
action2,
count(*) as total
from test
group by 1
)
select
nums.n,
coalesce(a1.total, 0) as Action1,
coalesce(a2.total, 0) as Action2
from nums
LEFT join action1_counts a1 on a1.action1 = nums.n
LEFT join action2_counts a2 on a2.action2 = nums.n
order by 1
答案 1 :(得分:0)
假设行动在0到6之间。
select a1.action, a1.action1, nullif(count(t2.action2),0) as action2
from
( select t.action, nullif(count(t1.action1),0) as action1
from
(select action from generate_series(0,6) g(action)) t
left join
test t1
on t1.action1 = t.action
group by t.action
) a1
left join
test t2
on t2.action2 = a1.action
group by a1.action, a1.action1
order by a1.action