2011-05-09 84 views
2

我需要根據2列名得到最大的行數。查詢以獲得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 
+0

在您的示例輸出中,爲什麼'SubPackName'用於印地語'H2'而不是'H1'?原始數據中都有「H1」和「H2」條目。在最終結果中使用哪一個是否重要? – jwd 2011-05-09 18:32:16

+0

@jwd我需要基於Pack和SUbpack顯示最大計數,這裏H2有3行,H1有1行,最大計數爲3 H2。 – Simhadri 2011-05-09 18:41:52

回答

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 
+0

它的工作感謝一百萬... – Simhadri 2011-05-09 19:43:35

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 
+0

感謝您的時間,我使用AJ01查詢得到了準確的結果。 – Simhadri 2011-05-09 19:44:28