简体   繁体   English

来自同一 SQL 表的不同列的不同行的输出

[英]output with different rows from different columns from the same SQL table

I'm trying to calculate running averages of past 4th month.我正在尝试计算过去 4 个月的运行平均值。 So I need to get the 4th value of each month所以我需要获得每个月的第 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

[Expected Output] [预期产出]

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

What I tried to do我试图做的

  • I tried to rank excluding zeros like row_number over (order by month desc) - that didn't work我试图对排除零之类的行进行排名(按月降序排列) - 没有用

-I tried to to use NULLS LAST function that didn't work either because I need to order based on month not on each month - 我尝试使用 NULLS LAST 函数也不起作用,因为我需要根据月份而不是每个月进行订购

Please help请帮忙

This is a very strange requirement.这是一个很奇怪的要求。 But you can do this using a window function to get the first non-zero rank.但是您可以使用窗口函数来获得第一个非零等级。 Then add three and use conditional aggregation:然后添加三个并使用条件聚合:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM