我有这样的桌子
| Id | ExternalId | Type | Date | StatusCode |
-------------------------------------------------------
| 1 | 123 | 25 | 2020-01-01 | A |
| 2 | 123 | 25 | 2020-01-02 | A |
| 5 | 125 | 25 | 2020-01-01 | A |
| 6 | 125 | 25 | 2020-01-02 | B |
| 3 | 124 | 25 | 2020-01-01 | B |
| 4 | 124 | 25 | 2020-01-02 | A |
如果存在B,则对于具有ExternalId
且具有Max(Date)
的每个StatusCode = B
,我只需要一行,否则StatusCode = A
因此,预期结果是
| Id | ExternalId | Type | Date | StatusCode |
-------------------------------------------------------
| 2 | 123 | 25 | 2020-01-02 | A | <--I take Max Date and the StatusCode of the same row
| 6 | 125 | 25 | 2020-01-02 | B | <--I take Max Date and the StatusCode of the same row
| 3 | 124 | 25 | 2020-01-02 | B | <--I take Max Date and B, even if the Status code of the Max Date is A
我希望我已经清楚了。
这里是我尝试编写的查询:
SELECT ExternalId, Type, EntityType, Max(Date) as Date
From MyTable
group by ExternalId, Type, EntityType
但是我无法完成。
据我对您的sql的了解,您还需要按Type和EntityType进行分组。如果正确,则可以为条件B写入最大值,为所有行写入另一个最大值,然后将这些结果用于isull或合并函数,如下所示:
Select
t.ExternalId
,t.Type
,t.EntityType
,isnull(
max(iif(t.StatusCode='B', t.Date, null))
,max(t.Date)
) as Date
From MyTable t
Group by
t.ExternalId
,t.Type
,t.EntityType
您想过滤而不是汇总。一种解决方案是使用row_number()
:
select *
from (
select
t.*,
row_number() over(partition by ExternalId order by StatusCode desc, Date desc) rn
from mytable t
) t
where rn = 1