如果存在,则按一个值分组;否则,按同一列的另一个值分组

问题描述 投票:0回答:1

我有这样的桌子

|  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-server group-by grouping
1个回答
0
投票

据我对您的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

0
投票

您想过滤而不是汇总。一种解决方案是使用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
© www.soinside.com 2019 - 2024. All rights reserved.