mysql - 输出来自同一个 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
我试图做的
- 我试图排除诸如 row_number 之类的零(按月 desc 排序) - 这没有用
- 我尝试使用无效的 NULLS LAST 函数,因为我需要根据月份而不是每个月订购
请帮忙
解决方案
这是一个非常奇怪的要求。但是您可以使用窗口函数来获得第一个非零排名。然后添加三个并使用条件聚合:
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
推荐阅读
- python - Python方法:如何接受单个对象或集合作为参数?
- python - 在 Pycharm 调试器中自动扩展自身
- php - 查询数组的每个元素并将它们显示为单独的数据
- java - 将毫秒转换为月和年无法正常工作
- android-studio - 无法在 Android Studio 中查看所有 Button 属性。
- android - 以 FrameLayout 作为根布局,在另一个视图之上添加视图,偏移量为 X,Y
- swift - 为所有 rest api 服务声明一个通用函数
- django - 如何访问父模型字段?
- python - 尽管具有相同的列,但 xgboost 中的 feature_names 不匹配
- android - build.gradle 依赖项具有相同的版本规范,但仍然显示混合版本错误