根据条件选择一个具有最大CreatedOn组的行

时间:2018-08-10 04:26:37

标签: sql sql-server

select 
    Container, CreatedOn, * 
from 
    Inventory_container 
where 
    container in (select IC.Container
                  from INVENTORY_CONTAINER IC
                  inner join CONTAINER C on IC.Container = C.Container
                  where C.ContainerClassID = '100000011' 
                  group by IC.Container
                  having count(IC.Container) >= 2)

以下是查询结果:

[1]: https://i.stack.imgur.com/ueMOO.png

您可以看到类似的容器有2行 我要选择包含最新创建的行。

请帮助编辑我的查询。

4 个答案:

答案 0 :(得分:1)

如果您使用的是SQL Server,请尝试以下查询:

SELECT *
FROM ( 
       SELECT *, ROW_NUMBER()OVER(PARTITION BY Container ORDER BY CreatedOn) AS RowNo
       FROM INVENTORY_CONTAINER IC INNER JOIN CONTAINER C ON 
       IC.Container=C.Container
       WHERE C.ContainerClassID='100000011' 
       GROUP BY IC.Container,CreatedOn
       HAVING COUNT(IC.Container)>=2
     ) AS T
WHERE RowNo = 1

答案 1 :(得分:1)

我认为子查询和联接可以为您提供帮助

 select iC.* from INVENTORY_CONTAINER IC inner join
         inner join
         (
          select IC.Container,max(IC.CreatedOn) as CreatedOn
          from INVENTORY_CONTAINER IC
          inner join CONTAINER C on IC.Container = C.Container
          where C.ContainerClassID = '100000011' 
          group by IC.Container
          having count(IC.Container) >= 2
          ) t on IC.Container=t.Container and IC.CreatedOn=t.CreatedOn

答案 2 :(得分:0)

您需要向查询中再写入一个子查询。

select 
   Container,CreatedOn, * 
from 
    Inventory_container 
where 
    container in (select IC.Container
                  from INVENTORY_CONTAINER IC
                  inner join CONTAINER C on IC.Container = C.Container
                  where C.ContainerClassID = '100000011' 
                  and IC.CreatedOn= 
                  (select max(IC1.CreatedOn) from INVENTORY_CONTAINER IC1
                   where IC1.container=IC.container));
                  group by IC.Container
                  having count(IC.Container) >= 2 ;

我假设根据数据库设计,您提到的查询在语法上是正确的。

答案 3 :(得分:0)

尝试以下查询-:

With CTE as
(
SELECT *, ROW_NUMBER()OVER(PARTITION BY Container ORDER BY CreatedOn desc) AS RN
       FROM INVENTORY_CONTAINER IC INNER JOIN CONTAINER C ON 
       IC.Container=C.Container
       WHERE C.ContainerClassID='100000011' 
       GROUP BY IC.Container
       HAVING COUNT(IC.Container)>=2
)select * from CTE where RN=1

SQL Server