微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

自定义分组依据并将一些记录放在一个分组中

如何解决自定义分组依据并将一些记录放在一个分组中

我正在使用,outer apply因此您不会将您的代码复制到组中

select
    C.Group_Name, count(*)
from Table1
    outer apply
    (
        select
            case
                when C.[Group] in (1, 2, 3) then 'Group for 1, 2, 3'
                when C.[Group] in (4, 5) then 'Group for 4, 5'
            end as Group_Name
    ) as C
group by C.Group_Name

您还可以使用子查询

select
    C.Group_Name, count(*)
from 
(
    select
        case
            when T.[Group] in (1, 2, 3) then 'Group for 1, 2, 3'
            when T.[Group] in (4, 5) then 'Group for 4, 5'
        end as Group_Name,
        T.Value,
        T.Id
    from Table1 as T
) as C
group by C.Group_Name

解决方法

请考虑数据:

 Id          Group            Value
 -----------------------------------
 1            1                10
 2            1                12
 3            1                10
 4            2                90
 5            2                10
 6            3                30
 7            4                12
 8            4                11
 9            5                10
 10           5                11

我想Group By将此数据1,2,3放在一个组中,4,5放在另一个组中。我该怎么做SQL Server

谢谢


编辑1)

我想要这个结果:

Groups                              Count
-----------------------------------------
Group for 1,3                       6
Group for 4,5                         4

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。