sql如何在同一查询中返回两个不同的日期

vkc1a9a2  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(383)

我有一个查询,我要做的是返回同一行中两列的最新日期。如果你看rowid1&2,我想合并这两行。它们都具有相同的事件类型,但不同之处在于isprocessed列中一个包含1,另一个包含0值。lastreceived列应返回isprocessed为0的最新日期,lastprocessed列应返回isprocessed为1的最后日期。现在我有工作,但它返回两行。第1行显示lastreceived为0的最后日期,第2行显示lastprocessed为1的最后日期。lastreceived和lastprocessed都来自createdon列。我需要在select子句中这样做

select MAX(select CreatedOn from mytable where IsProcessed=1) as LastProcessed,
MAX(select CreatedOn from mytable where IsProcessed=0) as LastReceived

下面是我的问题

with cte as (select distinct EventType,SendingOrganizationID,MAX(CreatedOn) as LastReceived,MAX(CreatedOn) as LastProcessed,case 
when SendingOrganizationID = '3yst8' then 'Example 1'
else 'Client Not Found'
END AS ClientName,IsProcessed from mytable
where  isprocessed in(0,1)
group by SendingOrganizationID,EventType,IsProcessed
having datediff(hour, MAX(CreatedOn), getdate()) >= 9)

Select ROW_NUMBER() over (ORDER BY SendingOrganizationID) as RowID,* from cte order by SendingOrganizationID,EventType,IsProcessed


有什么建议就好了

hlswsv35

hlswsv351#

在下列情况下可以使用case:

select EventType,SendingOrganizationID,
MAX(case when isProcessed = 0 then CreatedOn end) as LastReceived,
MAX(case when isProcessed = 1 then CreatedOn end) as LastProcessed
from mytable
group by SendingOrganizationID,EventType;

相关问题