【问题标题】:cumulative total in sqlsql中的累计总数
【发布时间】:2021-09-19 04:49:42
【问题描述】:

我有这张桌子。我需要数数:

  1. 累计积木总数(total_count)
  2. 每种颜色累计的积木数量 (running_total_per_colour)
brick_id     colour shape   weight
1            blue   cube    1
2            blue   pyramid 2
3            red    cube    1
4            red    cube    2
5            red    pyramid 3
6            green  pyramid 1

我怎样才能用 SQL 做到这一点

【问题讨论】:

  • 编辑您的问题并显示您想要的结果。
  • @GordonLinoff 是的,我正在寻找窗口函数。
  • @GordonLinoff 是的,非常感谢!

标签: mysql sql database oracle


【解决方案1】:

您只是在寻找窗口函数吗?

select t.*,
       row_number() over (order by brick_id) as cumulative_bricks,
       sum(case when colour = 'blue' then 1 else 0 end) over (order by brick_id) as blue_bricks,
       sum(case when colour = 'red' then 1 else 0 end) over (order by brick_id) as red_bricks,
       sum(case when colour = 'green' then 1 else 0 end) over (order by brick_id) as green_bricks
from t;

【讨论】:

    【解决方案2】:

    你在寻找这样的东西吗?

    SELECT A.*, COUNT(*) OVER() CUMMULATIVE_TOTAL,
    ROW_NUMBER() OVER(PARTITION BY COLOUR ORDER BY BRICK_ID) RUNNING_TOTAL
    FROM TABLE1 A;
    

    DB_FIDDLE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 2011-08-07
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多