【问题标题】:Find Column With Max on Other Column Grouping By Another Column在其他列上查找具有最大值的列 按另一列分组
【发布时间】:2021-01-01 10:43:33
【问题描述】:

我有一张这样的桌子:

Id   - ItemId -  Price   -  SalesId       -       Date
1       12      99.99924    21899234        2025-01-01 00:00:00.000000
2       123     12.34567    348923          2021-01-01 00:00:00.000000
3       1234    1234.5      3321234         2022-01-01 00:00:00.000000
4       12345   3.3246      2154234         2023-01-01 00:00:00.000000
5       1234    451.234     3423            2020-02-01 00:00:00.000000
6       12345   0.989       71112357        2020-09-15 20:20.10.000000
7       123     3435.3      71112357        2020-09-14 20:10:12.000000

我正在尝试用最新的Date 查找ItemPrice。例如,如果我们试图找到ItemId = 1234,日期最晚的是这个2022-01-01 00:00:00.000000,它有Id = 3,它的价格是1234.5。这就是我试图通过这个查询找到的,这个项目的价格。

我是 SQL 的初学者并尝试了以下查询,但它给了我这个错误:

select "ItemId",
       max("Date"),
       "Price"
from "Products"
group by "ItemId"

[42803] 错误:列“Products.Price”必须出现在 GROUP BY 子句中或用于聚合函数中

感谢您的帮助。谢谢!

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    在 Postgres 中,你可以使用distinct on:

    select distinct on ("ItemId") p.*
    from "Products" p
    order by "ItemId", "Date" desc;
    

    注意:如果您正在学习 SQL,请不要在字符串和列名中使用双引号。

    【讨论】:

    • 感谢 Gordon 的回答,但它给了我这个错误:[42601] ERROR: syntax error at or near "desc" in a PostgreSQL 数据库。我正在使用 DataGrip。
    • 如果我删除desc,它会给我一个不同的错误:[42803] 错误:列“p.Id”必须出现在 GROUP BY 子句中或用于聚合函数.
    • @N.Dogac 将 group by 更改为 order by
    【解决方案2】:

    您可以尝试使用row_number()

    select * from
    (
    select ItemId,Date,Price,row_number() over(partition by itemid order by date desc) as rn
    from Products
    )A where rn=1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-10
      • 2013-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      相关资源
      最近更新 更多