【问题标题】:Group By and get distinct value that occurs most often分组并获得最常出现的不同值
【发布时间】:2012-01-15 17:46:35
【问题描述】:

我想按一个 varchar 列分组并找到出现次数最多的外键值。问题是可以将多个 fiModel 分配给同一个 TAC(称为 SSN_Number 的 15 位值的前 8 位)。

这是一个简化的模型和带有样本数据的查询:

create table #data(
    SSN_Number varchar(15),
    fiModel int
)
insert into #data
        SELECT '351806038155151',451 UNION ALL SELECT '353797028764243',232 UNION ALL SELECT '353797028764243',438 UNION ALL SELECT '353797028764243',438 UNION ALL SELECT '353797028764243',447 UNION ALL SELECT '358372015611578',318 UNION ALL SELECT '352045039834626',279 UNION ALL SELECT '352045031234567',279 UNION ALL SELECT '351806035647381',451 UNION ALL SELECT '352045037654321',207

--- following query returns all records(10)
select * from #data Order By SSN_Number

--- following query gives the distinct TAC's+fiModel, but TACs can repeat (9)
select substring(ssn_number,1,8)as TAC,fiModel,count(*) from #data
group by substring(ssn_number,1,8),fiModel
Order By substring(ssn_number,1,8),fiModel

--- following query gives the correct(distinct) TAC's (4), 
--- but i need the fiModel that occurs most often with the assigned TAC
--- if the number is the same, it doesn't matter what to take
select substring(ssn_number,1,8)as TAC,count(*) from #data
group by substring(ssn_number,1,8)
Order By substring(ssn_number,1,8)

drop table #data

所以这是想要的结果:

TAC         fiModel
35180603    451
35204503    279
35379702    438
35837201    318

【问题讨论】:

    标签: sql sql-server-2005 group-by


    【解决方案1】:

    这应该可以解决问题(CTE 的救援!):

    ;with cte as (
        select substring(ssn_number,1,8) as TAC, fiModel, ROW_NUMBER() OVER (PARTITION BY substring(ssn_number,1,8) ORDER BY count(*) desc) as row
        from #data
        group by substring(ssn_number,1,8),fiModel
    )
    select TAC, fiModel
    from cte
    where row = 1
    

    作为子查询:

    Select TAC,fiModel
    from(
        Select substring(ssn_number,1,8)as TAC, fiModel
          ,ROW_NUMBER() OVER (PARTITION BY substring(ssn_number,1,8) ORDER BY count(*) desc) as row
        from #data
        group by substring(ssn_number,1,8),fiModel
    )as data
    where row=1
    

    【讨论】:

    • 谢谢。编辑了您的答案以提供子查询方法,这可能更好地集成到我的实际查询中。
    猜你喜欢
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 2017-02-17
    • 1970-01-01
    相关资源
    最近更新 更多