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

无窗口函数下的多分组SQL数据处理需求:关联用户表聚合收入并按子用户+小时维度取最大值

Solution for Multi-Group Aggregation Without Window Functions

Since window functions aren't available on your remote server, we can fix this by first pre-processing the revenuetb table to eliminate duplicate subuser + hour records (keeping only the maximum revenue for each pair), then joining that cleaned data with usertable.

Here's the modified SQL query that meets all your requirements:

SELECT 
    u.Username,
    COALESCE(SUM(mr.Max_Revenue), 0) AS Total_Usage
FROM usertable u
LEFT JOIN (
    -- Step 1: Get max revenue per subuser + hour pair to remove duplicates
    SELECT 
        subuser,
        hour,
        MAX(Revenue) AS Max_Revenue
    FROM revenuetb
    WHERE hour BETWEEN 'XXX' AND 'XXX' -- Keep your original date range filter here
    GROUP BY subuser, hour
) mr ON SUBSTRING_INDEX(mr.subuser, '_', 1) = u.Username
WHERE u.Status = 'Active'
GROUP BY u.Username, u.ID -- Include u.ID to comply with strict SQL modes and ensure correct ordering
ORDER BY u.ID;

Breakdown of the changes:

  • Subquery mr: This inner query groups revenuetb by subuser and hour, grabbing the maximum Revenue for each unique pair. This eliminates duplicate entries like the two Mike_01 records at 7:00, retaining only the 22 value.
  • Left Join: We join this cleaned dataset with usertable using the subuser prefix match, ensuring even Active users with no revenue history (like Lena and Lara) show up in the results.
  • COALESCE: Converts NULL values (from users with no matching revenue records) to 0, which aligns perfectly with your desired output.
  • GROUP BY & ORDER BY: Adding u.ID to the GROUP BY clause ensures we can safely sort by user ID later (some strict SQL modes require all non-aggregated columns in the SELECT to be included in GROUP BY).

Check against your target output:

  • John gets 5 (single valid record)
  • Mike gets 22 (max of his duplicate hour entries)
  • Leta gets 67 + 56 = 123 (sum of max values for her two subuser-hour pairs)
  • Lena and Lara get 0 (no revenue records)
  • Mitch gets 34 (single valid record)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 14:27:43