SQL查询以获取每个类别最多的值

时间:2011-11-13 22:35:50

标签: sql pivot

我有一张这样的表:

Category    Reply
---------+---------------+
M             1                
F             2                
M             1                
M             3             
M             1                
M             3                
F             2                
F             1                
F             2             
F             5
F             2

我正在寻找一个SQL查询来返回以下结果:

Category   Total Number    Best Reply           Number
---------+---------------+------------------+---------------+
M             5                  1                 3
F             6                  2                 4

总数:该类别的出现次数(我知道如何获得)

最佳回复:为该类别选择最多的回复

数字:选择“最佳回复”的次数

2 个答案:

答案 0 :(得分:1)

您没有指定数据库,所以我避免使用公用表表达式,这会使这个更清晰。它仍然可以清理一下。我在SQL Server 2008上完成了我的工作。

select  rsTotalRepliesByCategory.Category, 
        TotalRepliesByCategory,
        rsCategoryReplyCount.Reply,
        rsMaxReplies.MaxReplies
from
(
    --calc total replies
    select  Category, COUNT(*) as TotalRepliesByCategory
    from CategoryReply
    group by Category
) rsTotalRepliesByCategory
INNER JOIN
(
    --calc number of replies by category and reply
    select Category, Reply, COUNT(*) as CategoryReplyCount
    from CategoryReply
    group by Category, Reply
) rsCategoryReplyCount on rsCategoryReplyCount.Category = rsTotalRepliesByCategory.Category
INNER JOIN 
(
    --calc the max replies
    select Category, MAX(CategoryReplyCount) as MaxReplies
    from
    (
        select Category, Reply, COUNT(*) as CategoryReplyCount
        from CategoryReply
        group by Category, Reply
    ) rsCategoryReplyCount2
    group by Category
) rsMaxReplies on  rsMaxReplies.Category = rsTotalRepliesByCategory.Category and rsMaxReplies.MaxReplies = rsCategoryReplyCount.CategoryReplyCount

以下是我过去常用的设置:

create table CategoryReply
(
    Category char(1),
    Reply int
)

insert into CategoryReply values ('M',1)
insert into CategoryReply values ('F',2)
insert into CategoryReply values ('M',1)
insert into CategoryReply values ('M',3)
insert into CategoryReply values ('M',1)
insert into CategoryReply values ('M',3)
insert into CategoryReply values ('F',2)
insert into CategoryReply values ('F',1)                
insert into CategoryReply values ('F',2)
insert into CategoryReply values ('F',5)
insert into CategoryReply values ('F',2)

最后,输出:

Category    TotalRepliesByCategory  Reply   MaxReplies
F   6   2   4
M   5   1   3

答案 1 :(得分:0)

SELECT    Category, TotalNumber, Row_Number() over (order by TotalNumber)
FROM(

    SELECT Category, Sum(Reply) as TotalNumber,  Count(Reply) as Number
    From Table
    Group By Category) as temp

会是那样的