Sql 如何获得每个“的平均值”;“类型”;在列中,而忽略具有相同用户ID的列
我有两个表,一个事件表和一个用户表Sql 如何获得每个“的平均值”;“类型”;在列中,而忽略具有相同用户ID的列,sql,postgresql,Sql,Postgresql,我有两个表,一个事件表和一个用户表 events table: id | event_type | user_id -------------------------- 1 | 'type 1' | 1 2 | 'type 1' | 1 3 | 'type 1' | 4 4 | 'type 1' | 4 5 | 'type 1' | 3 6 | 'type 2' | 1 7 | 'type 4' | 2 我试图从所有用户(除1个特定用户外)获取所有事
events table:
id | event_type | user_id
--------------------------
1 | 'type 1' | 1
2 | 'type 1' | 1
3 | 'type 1' | 4
4 | 'type 1' | 4
5 | 'type 1' | 3
6 | 'type 2' | 1
7 | 'type 4' | 2
我试图从所有用户(除1个特定用户外)获取所有事件类型的平均值。
因此,看看我上面给出的示例表,如果type1
在3个唯一用户之间显示5倍,但我想忽略user\u id=3
,那么它将在2个用户之间显示总共4倍,因此type1
的平均值将为2。每种类型我都需要这个
这是我到目前为止的SQL查询:
SELECT *
FROM events
LEFT JOIN users
ON users.id = events.user_id
WHERE users.username != 'a username'
这仅获取除给定用户名之外的所有事件。但现在我需要找到所有事件类型的平均值
我感谢你的帮助 您可以这样做,只需稍微调整一下查询
SELECT event_type, count(distinct events.user_id)
FROM events
LEFT JOIN users
ON users.id = events.user_id
WHERE users.username != 'a username'
group by event_type
啊,你在追求平均水平。。试试这个
SELECT e.event_type, COUNT(e.user_id) / COUNT(DISTINT e.user_id) [AverageUsers]
FROM events e
LEFT JOIN users u ON u.id = e.user_id
WHERE u.username != 'a username'
GROUP BY e.event_type;
请注意,这将给出一个整数作为平均数,因为我们用整数除以整数。如果您想要十进制平均值,则需要执行以下操作:
SELECT e.event_type, COUNT(e.user_id) / (COUNT(DISTINT e.user_id) * 1.0) [AverageUsers]
FROM events e
LEFT JOIN users u ON u.id = e.user_id
WHERE u.username != 'a username'
GROUP BY e.event_type;
您只需要events
表和event\u type
列即可获得所需的集合:
select event_type, (count(*)::float/(select count(*) from events)) as average_nr_of_types
from events
group by event_type
你在数什么?用户数量?如果是这样,您需要选择events.id,COUNT(users.id)作为user\u COUNT,不要忘记按events.id分组。在这里阅读更多内容:好的,也许不需要计数。您是否需要像类型1->0.71,类型2->0.14,类型4->0.14这样的输出集?@BarbarosÖzhan-Yup。同时忽略输入的用户名!这并没有完全封装我正在寻找的内容。修改了我的答案,sssyn,每个事件类型,您需要一个计数,对吗?我确实需要用户表,因为我需要忽略特定的用户。在使用代码编辑后,我能够使它工作(我想!)谢谢!嗯,运行您的查询会为每种类型提供“1.0”。我不得不删除[AverageUsers]
,因为我的pgAdmin抛出了一个错误。
select event_type, (count(*)::float/(select count(*) from events)) as average_nr_of_types
from events
group by event_type