0

我有一个带有列的表: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

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

这仅仅是用 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
;
4

2 回答 2

1

您想使用 ajoin而不是变量来执行此操作。这个想法是按年-季-目录和年-季汇总数据,然后将结果结合在一起进行算术:

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;
于 2013-07-23T22:41:19.643 回答
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
于 2017-09-08T08:07:09.543 回答