按类别SQL查询的相对频率

时间:2013-07-23 22:32:51

标签: mysql sql sum aggregate-functions

我有一个包含列的表:date, category, views

我想写一个查询,它给出了以下输出:

year, quarter, category, "relative percentage of category views by quarter"

例如:

2013, Q1, blue, 0.15
2013, Q1, yellow, 0.05
2013, Q1, green, 0.80
2013, Q2, blue, 0.20
2013, Q2, yellow, 0.05
2013, Q2, green, 0.75
2013, Q3, blue, 0.10
2013, Q3, yellow, 0.15
2013, Q3, green, 0.65

请注意,对于每个季度,相对频率在整个类别中加起来为

这只是太多的状态,只用SQL动态处理(我使用的是MySQL)?

这是我到目前为止所拥有的。

这几乎是我想要的,除了所有季度的相对频率输出总和为1。

SET @total_views = SELECT sum(views) FROM daily_views_by_category;

SELECT
    year(dt),
    quarter(dt),
    category,
    sum(views)/@total_views AS category_views
FROM
    daily_views_by_category
GROUP BY
    year(dt), quarter(dt), category
ORDER BY
    year(dt), quarter(dt), category
;

2 个答案:

答案 0 :(得分:1)

您希望使用join而非变量执行此操作。我们的想法是按年度目录和年度季度汇总数据,然后将结果加在一起进行算术运算:

SELECT yqc.yr, yqc.qt, category,
       (yqc.views / yq.views) as category_views
FROM (select year(dt) as yr, quarter(dt) as qt, category, sum(views) as views
      from daily_views_by_category vbc
      group by year(dt), quarter(dt), category
     ) yqc join
     (select year(dt) as yr, quarter(dt) as qt, sum(views) as views
      from daily_views_by_category vbc
      group by year(dt), quarter(dt)
     ) yq
     on yqc.yr = yq.yr and yqc.qt = yq.qt
ORDER BY 1, 2, 3;

答案 1 :(得分:0)

使用聚合函数的情况。从MySQL 8.0.2开始,引擎支持聚合/窗口函数,但我还没有对它进行测试。

SELECT year(dt)
       ,quarter(dt)
       ,category
       ,SUM(views) 
       ,SUM(views)*1.0/SUM(SUM(views)) OVER (PARTITION BY year(dt), quarter(dt))
  FROM daily_views_by_category
 GROUP BY 
       year(dt)
       ,quarter(dt)
       ,category