我有一个包含这样数据的表:
event | session id | uid
---------------------
foo | 1 | a
bar | 1 | a
foo | 2 | b
cat | 2 | b
cat | 3 | a
cat | 4 | c
foo | 5 | c
cat | 5 | c
foo | 6 | b
foo | 7 | a
dog | 8 | c
dog | 9 | b
bat | 10 | c
我想创建一个查询以按以下格式返回结果:
uid | event | # event used | # of sessions for uid
a | foo | 2 | 4
a | bar | 1 | 4
a | cat | 1 | 4
b | foo | 2 | 4
b | cat | 1 | 4
b | dog | 1 | 4
c | cat | 2 | 5
c | foo | 1 | 5
c | dog | 1 | 5
c | bat | 1 | 5
我尝试使用:
select uid, event, count(*) from events where uid in (select uid from events group by uid) group by uid;
但是没有按预期工作。
非常感谢任何帮助。
答案 0 :(得分:1)
select t1.uid, t1.event, count(*) as `# event used`, t2.total_events as `# of sessions for uid`
form table t1
inner join (
select uid, count(*) as total_events
from table
group by uid
) t2 on t2.uid = a.uid
group by t1.uid, t1.event, t2.total_events
order by t1.uid, `# event used` desc
答案 1 :(得分:0)
这可以通过 CASE 语句来实现:
select uid, count(case when event=`foo` then uid else 0 end) as `foo`,
count(case when event=`bar` then uid else 0 end) as `bar`,
count(case when event=`cat` then uid else 0 end) as `cat`,
count((case when event=`foo` then uid else 0 end) + count(case when event=`bar` then uid else 0 end) + count(case when event=`cat` then uid else 0 end)) as totaL_events`
from events group by 1;
这会给你一个这样的表:
uid | foo | bar | cat | total_events
a 2 1 1 4
b 2 1 1 4
对于其他表,请使用:
select uid, event, count(uid) as event_used from events group by 1, 2
这里的表格不那么花哨:
uid | event | total_events
a foo 2
a bar 1
b foo 2
请记住,根据您的要求,总结每个用户在每个不同情况下的事件总数是不可能或最不高效的,只需通过uid和事件类型即可实现。