sql group by and max 和其他值

sql group by and max and other values

我有一个 table 包含:

itemid inventdimid datephysical transrefid
10001   123         2015-01-02   300002
10002   123         2015-01-03    3566
10001   123         2015-02-05    55555
10002   124         2015-02-01     4545

我想要的结果

itemid inventdimid datephysical transrefid
10001   123           2015-02-05   555
10002   123           2015-01-03    3566
 10002   124         2015-02-01     4545

我的查询:

SELECT a.itemid,a.inventdimid,max(a.datephysical),a.transrefid
  FROM  a where dataareaid = 'ermi' 
group by a.itemid,a.inventdimid

它在 select 列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。

为每个 itemid、inventdimid 组合查找 max(a.datephysical),select 从该日期开始的所有行。

SELECT itemid, inventdimid, datephysical, transrefid
FROM  a a1
where dataareaid = 'ermi'
  and datephysical = (select max(datephysical)
                      from a a2
                      where a1.itemid = a2.itemid
                        and a1.inventdimid = a2.inventdimid
                        and a2.dataareaid = 'ermi')         

您必须用您的 GROUP BY 创建一个临时 table,然后用它加入原来的 table。

试试这个:

SELECT T1.*,T2.datephysical,T2.transrefid FROM 
(SELECT itemid,inventdimid 
         FROM TableName 
         GROUP BY itemid,inventdimid) T1 JOIN
(SELECT itemid,inventdimid,datephysical,transrefid
 FROM TableName) T2 ON T1.itemid=T2.itemid AND T1.inventdimid=T2.inventdimid

我假设您想要与显示的 a.datephysical 相对应的 transrefid?这可以通过将列转换为子查询来完成:

SELECT a.itemid,a.inventdimid,max(a.datephysical),
(SELECT b.transrefid FROM MY_TABLE b where
b.datareaid = 'ermi' and b.itemid = a.itemid and b.inventdimid = a.itemid
and b.datephysical = max(a.datephysical)) as transrefid
FROM MY_TABLE a where dataareaid = 'ermi' 
group by a.itemid, a.inventdimid

有些数据库可能不支持这种语法,如果有多个记录具有相同的日期,它就会失败。

使用ANSI标准row_number()函数:

select t.*
from (select t.*,
             row_number() over (partition by itemid, inventdimid
                                order by datephysical desc) as seqnum
      from table t
     ) t
where seqnum = 1;