【问题标题】:Select one row, each one id in sql query for odoo在odoo的sql查询中选择一行,每个id
【发布时间】:2023-03-27 10:58:01
【问题描述】:

我有一张这样的桌子:

 ID |     Cost     | Month |  Year  |
-------------------------------------
1081|     13000    |   5   |  2017  |
1081|     13500    |   9   |  2016  |
1081|     21000    |   2   |  2016  |
1229|     6500     |   7   |  2017  |
1229|     7800     |   5   |  2016  |
1312|    110000    |   8   |  2017  |
1312|    120000    |   5   |  2017  |
1312|     99000    |   5   |  2016  |

我试过了:

select id, year, month, avg(cost) as Avg Cost
from price_history
group by id, year, month
order by id, year desc, month desc

我怎样才能像这样显示最新数据:

 ID |     Cost     | Month |  Year  |
-------------------------------------
1081|     13000    |   5   |  2017  |
1229|     6500     |   7   |  2017  |
1312|    110000    |   8   |  2017  |

【问题讨论】:

  • 我从您的输出示例中无法理解 - 您需要 AVG 成本还是什么?
  • 我只想要基于月份和年份的最新数据/行。

标签: sql postgresql greatest-n-per-group odoo-8


【解决方案1】:
select id, year, month, cost
  from (
    select id, year, month, cost,
           row_number() over(partition by ID order by year desc, month desc) as RN
      from price_history
 ) X
 where RN=1

【讨论】:

    【解决方案2】:

    结合使用RIGHT/LEFTMAX 和串联函数来正确分组日期。

    SELECT "ID", AVG("Cost") AS "Avg Cost", RIGHT(MAX("Year"::text || "Month"::text),1) AS "Month", LEFT(MAX("Year"::text || "Month"::text),4) AS "Year"
    FROM price_history
    GROUP BY "ID"
    ORDER BY "ID"
    

    输出

    ID   Avg Cost           Month Year
    1081 15833.333333333332 5     2017
    1229 7150               7     2017
    1312 109666.66666666667 8     2017
    

    SQL 小提琴:http://sqlfiddle.com/#!15/3ebe7/20/0

    或者ROUNDing:

    SELECT "ID", ROUND(AVG("Cost")) AS "Avg Cost", RIGHT(MAX("Year"::text || "Month"::text),1) AS "Month", LEFT(MAX("Year"::text || "Month"::text),4) AS "Year"
    FROM price_history
    GROUP BY "ID"
    ORDER BY "ID"
    

    输出

    ID   Avg Cost Month Year
    1081 15833    5     2017
    1229 7150     7     2017
    1312 109667   8     2017
    

    SQL 小提琴:http://sqlfiddle.com/#!15/3ebe7/21/0

    【讨论】:

    • 如果成本不平均怎么办?
    • @FadhelJMuhammad ??你问的是平均成本?
    • 不,我只想获取最新数据。我被编辑列成本
    • @FadhelJMuhammad 我会怎么知道?你没有在你的问题中这么说。
    • 对不起,如果我的问题让您感到困惑。谢谢你的回答:)
    猜你喜欢
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    • 2018-01-27
    • 2012-10-15
    • 2010-10-08
    • 2011-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多