如何使用CASE条件过滤双重数据?

问题描述

首先为我试用Stack,如果我在此处不符合要求的代码,请随时反馈。

我正在一个表格中处理财务信息和大量收入,处于不同的截止日期。

我想返回ID,截止日期,最新收入。

我做到了

SELECT A.ID,A.closing_date,A.operating_revenue_
From financials A

INNER JOIN(
      SELECT ID,max(closing_date) as Latest_Date
      FROM financials
      GROUP BY ID
)tm on A.ID=tm.ID and A.closing_date=tm.Latest_Date

现在,我的问题是我有双重数据,具体取决于财务数据中的合并代码。我碰巧同时有未合并和合并的数据,代码为U1,C1。

如果我拥有这两个代码的数据,只需重新获取合并的代码,您是否知道如何处理? The issue appears at 31 and 32

我正在尝试使用CASE函数

WHERE A.consolidation code in ('C1','U1')
AND (Case A.consolidation_code in 'U1' or 'C1',then 'C1'
ELSE 'U1'
END)
```

The latest seems the issue,has anyone an idea of what is the issue and how I Could solve it?
Thank you


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

解决方法

使用row_number() over()并假设ID,closing_date,operating_revenue_,consolidation_code是唯一键,并基于事实'C1' 'U1'

select A.ID,A.closing_date,A.operating_revenue_
from (
    select f.*,row_number() over(partition by ID,operating_revenue_ order by consolidation_code) rn
    from financials f
    where consolidation_code in ('C1','U1')
) A
where a.rn = 1