首页 > 解决方案 > 输出来自同一个 SQL 表的不同列的不同行

问题描述

我正在尝试计算过去 4 个月的运行平均值。所以我需要得到每个月的第四个值

month_date | Month 1 | Month 2 | Month 3| Month 4
---------------------------------------------
 11   |   0    |   0     |   0    |   0
 10   |   2    |   0     |   0    |   0
 09   |   3    |   4     |   0    |   0
 08   |   8    |   7     |   9    |   0
 07   |   6    |   8     |   11   |   5
 06   |   3    |   4     |   0    |   8
 05   |   8    |   7     |   9    |   9
 04   |   6    |   8     |   11   |   5

[预期输出]

 | Month 1 | Month 2 | Month 3| Month 4
----------------------------------------
  |   6     |   4     |   9    |   5

我试图做的

- 我尝试使用无效的 NULLS LAST 函数,因为我需要根据月份而不是每个月订购

请帮忙

标签: mysqlsqldatabaseoracleranking-functions

解决方案


这是一个非常奇怪的要求。但是您可以使用窗口函数来获得第一个非零排名。然后添加三个并使用条件聚合:

select max(case when rank = month1_rank0 + 3 then month1 end) as month1,
       max(case when rank = month2_rank0 + 3 then month2 end) as month2,
       max(case when rank = month3_rank0 + 3 then month3 end) as month3,
       max(case when rank = month4_rank0 + 3 then month4 end) as month4       
from (select t.*,
             min(case when month1 <> 0 then rank end) over () as month1_rank0,
             min(case when month2 <> 0 then rank end) over ()  as month2_rank0,
             min(case when month3 <> 0 then rank end) over ()  as month3_rank0,
             min(case when month4 <> 0 then rank end) over ()  as month4_rank0
      from t
     ) t

推荐阅读