简体   繁体   English

SQL查询加入问题

[英]SQL query joining issue

I have two tables login_activity and event_details . 我有两个表login_activityevent_details The structure of the tables is as below: 表的结构如下:

Login_activity
activity_id   |  student_id   |  login_date  | event_id

event_details
event_id   |  event_name   |  event_date

I need to fetch the event_id and the count of student_id from login_activity that match the event_id . 我需要从login_activity获取与event_id匹配的event_idstudent_id计数。

I tried the below query 我尝试了以下查询

select event_id,student_id 
from login_activity 
where login_activity.event_id in (select event_id from event_details);

But I am not able to get distinct event_id and count of student_ids for those. 但是我无法获得不同的event_id和student_ids的数量。 I know there has to be a simple solution, but I can't seem to get it. 我知道必须有一个简单的解决方案,但我似乎无法得到它。 What am I missing? 我错过了什么?

You need to use a GROUP BY and COUNT 您需要使用GROUP BY和COUNT

SELECT l.event_id, count(student_ID)
FROM login_activity l
 INNER JOIN event_details e ON l.event_id = e.event_id
GROUP BY l.event_id

You actually don't need the event_details table, unless you want to pull in a specific event_name or event_date 实际上您不需要event_details表,除非您想要引入特定的event_name或event_date

SELECT l.event_id, count(student_ID)
FROM login_activity l
GROUP BY l.event_id

我相信你想在WHERE子句之后使用'GROUP BY student_id'。

Do you need the event_details table at all for your results (ie, do you need to use the name or the date of the event in your query)? 您是否需要event_details表来获得结果(即,您是否需要在查询中使用事件的名称或日期)? If not, you can just use the login_activity table: 如果没有,您可以使用login_activity表:

    select event_id, count(student_id) as student_count from login_activity group by event_id

If you were wanting the name of the event, it's still much the same, though. 如果你想要这个活动的名字,它仍然大致相同。

    select e.event_name, count(l.student_id) as student_count
    from event_details e
    left join login_activity l on e.event_id = l.event_id
    group by e.event_name

The advantage of the left join above is that you can get results for events that do not have any login activity yet, if that's applicable. 上面左连接的优点是,如果适用,您可以获得没有任何登录活动的事件的结果。 And you can replace event_name with event_id or the date as appropriate. 您可以根据需要将event_name替换为event_id或日期。

YOu need either an inner join or a left join to combine the data to get what you need. 你需要一个内部联接或一个左联接来组合数据以获得你需要的东西。 Then you can use group by and use your event id. 然后,您可以使用group by并使用您的事件ID。 To get the count you can use the count command and you can do as a new field for example count(l.student_id) as studentCount. 要获得计数,您可以使用count命令,您可以将新字段作为例如count(l.student_id)作为studentCount。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM