You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于COUNT、DISTINCT、CASE WHEN、LEFT OUTER JOIN的双表SQL查询需求

Got it! Let's build a practical SQL query that hits all your required clauses/functions while solving a meaningful business problem. First, let's recap our table structures clearly:

Users Table

user_idcompany
1Apple
2Microsoft

Sessions Table

session_iduser_idstart_timeend_timeuser_agent
1112:00:0012:20:00X
2114:10:0014:14:00Y

Let's say we want to calculate company-level user and session metrics: total unique users, users who have at least one session, session counts broken down by user agent, and total sessions per company. Here's the query that uses all your required components:

SELECT
    u.company,
    COUNT(DISTINCT u.user_id) AS total_unique_users,
    COUNT(DISTINCT CASE WHEN s.session_id IS NOT NULL THEN u.user_id END) AS users_with_active_sessions,
    COUNT(CASE WHEN s.user_agent = 'X' THEN s.session_id END) AS session_count_agent_x,
    COUNT(CASE WHEN s.user_agent = 'Y' THEN s.session_id END) AS session_count_agent_y,
    COUNT(s.session_id) AS total_sessions_per_company
FROM
    users u
LEFT OUTER JOIN
    sessions s ON u.user_id = s.user_id
GROUP BY
    u.company;

Breakdown of the required components:

  • LEFT OUTER JOIN: Ensures we keep every user from the users table, even if they have no matching sessions (like Microsoft's user ID 2). This prevents us from excluding users with zero activity.
  • COUNT(DISTINCT): Used in total_unique_users to count each user only once, even if they have multiple sessions. We also use it in users_with_active_sessions to avoid counting the same user multiple times for their multiple sessions.
  • CASE WHEN: Lets us apply conditional logic to our counts. For example, session_count_agent_x only counts sessions where the user agent is "X", and users_with_active_sessions only counts users who have at least one session record.
  • COUNT: Works alongside the above to aggregate our conditional and non-conditional metrics.

Expected Query Result

companytotal_unique_usersusers_with_active_sessionssession_count_agent_xsession_count_agent_ytotal_sessions_per_company
Apple11112
Microsoft10000

内容的提问来源于stack exchange,提问作者tshaw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:47:27