簡體   English   中英

如何獲取 sql 中唯一列的 MAX 值並聚合其他?

[英]How to get the MAX value of unique column in sql and aggregate other?

我想獲得具有最大“日期”的行,僅通過唯一的“id”分組但不考慮其他列。

我試過這個查詢:(但不工作導致修改其他列)

SELECT id,
       MAX(num),
       MAX(date),-- I just want the max of this column
       MAX(product_name),
       MAX(other_columns)
FROM TB
GROUP BY id

桌子:

id    num      date      product_name   other_columns
123   0001   2021-12-01      exit          12315413
123   0002   2021-12-02      entry         65481328
333   0001   2021-12-03      entry         13848136
333   ASDV   2021-12-04      exit           1325165

預期結果:

id    num      date      product_name
123   0002   2021-12-02      entry
333   ASDV   2021-12-04      exit

怎么做?

具有內部連接的子查詢可以不可知地處理這個漂亮的 DBMS。

SELECT
      t.ID
      ,t.date
      ,t.product_name
      ,t.other_columns
    FROM tb as t
    INNER JOIN (
       SELECT
          id
          ,MAX(date) as date
       FROM tb
       GROUP BY id 
    ) as s on t.id = s.id and t.date = s.date

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM