查询以获得2列最高最大值顺序?

时间:2011-05-09 18:24:51

标签: sql-server

我需要根据2个列名获得最大行数。

我有如下表格数据

Num     Pack   SubPack
98989   Hindi   H1
1234    Hindi   H2
1111    Hindi   H2
11213   English E1
13252   English E2
8664    ENglish E1
32141   Hindi   H2

我需要获得如下所示的输出

PackName SubPackName Count

Hindi       H2        3
English     E1        2 

以下是我使用的查询

With Q As(Select Count(*) as MobNos,PackName,SUbpackname
From tblCaller
Group By PackName,SUbpackname )
Select Packname,SUbPackname,Max(MobNos) as MaxCount From Q
Group By PackName,SUbpackname
Order By MaxCount Desc

2 个答案:

答案 0 :(得分:1)

您应该能够通过将Q连接到自身并且仅显示具有给定包/子包组合的最大计数的行来执行此操作。有一种更优雅的方式可以做到这一点,但是直到你找到它为止这一步!

With Q As(
  Select Count(*) as MobNos,PackName,SubPackName
  From tblCaller
  Group By PackName,SubPackName
)
select q1.PackName,q2.SubPackName,MAX(q1.MobNos) 'Total'
from
    Q q1
    join Q q2 on q1.PackName = q2.PackName
group by q1.PackName, q2.SubPackName, q2.MobNos
having q2.MobNos = MAX(q1.mobnos)
order by total desc

答案 1 :(得分:0)

我在SQLite中试过这个,我相信你可以为SQLServer修改它。

由于它有重复的子查询,因此有点粗略。您可以使用'WITH'子句,视图或临时表来避免这种情况。

注意:这与AJ01的答案基本相同。

SELECT
    SubPackCounts.*
FROM
    -- Make a subquery with counts grouped by subpacks
    (SELECT
        PackName,
        SubPack,
        COUNT(SubPack) AS Count
    FROM
        tblCaller
    GROUP BY SubPack
    ) AS SubPackCounts
    ,
    -- Make a subquery that has PackName and the associated max subpack count
    (SELECT
        PackName,
        MAX(Count) AS MaxCount
    FROM
            -- Note: this is the same sub-query as above
        (SELECT
            PackName,
            SubPack,
            COUNT(SubPack) AS Count
        FROM
            tblCaller
        GROUP BY SubPack
        ) AS SubPackCounts
    GROUP BY PackName
    ) AS PackMax
WHERE
    -- Only show results that are max
    SubPackCounts.Count = PackMax.MaxCount
GROUP BY PackName   -- Remove duplicates in the case of ties