获取单个查询中记录的计数百分比

时间:2011-09-07 20:39:59

标签: sql sql-server sql-server-2008

参考这个问题:

Get count of items and their values in one column

如何在单个查询中获得记录计数的百分比,如下所示:

ItemId        count          Percent
------------------------------------
   1            2              33.3
   2            0                0
   3            1              16.6
   4            3              50.0            

谢谢

4 个答案:

答案 0 :(得分:13)

COUNT(*) OVER()为您提供总计数。

修改但实际上您需要SUM(COUNT(MyTbl.ItemID)) OVER(),因为您要汇总该列中的值。

SELECT Items.ItemID,
       [count] = COUNT(MyTbl.ItemID),
       [Percent] = 100.0 * COUNT(MyTbl.ItemID) / SUM(COUNT(MyTbl.ItemID)) OVER()
FROM   (VALUES (1,'N1'),
               (2,'N2'),
               (3,'N4'),
               (4,'N5')) Items(ItemID, ItemName)
       LEFT JOIN (VALUES(1),
                        (1),
                        (3),
                        (4),
                        (4),
                        (4)) MyTbl(ItemID)
         ON ( MyTbl.ItemID = Items.ItemID )
GROUP  BY Items.ItemID
ORDER  BY Items.ItemID  

答案 1 :(得分:4)

select
    ItemId,
    count(*) as count,
    cast(count(*) as decimal) / (select count(*) from myTable) as Percent 
from myTable
group by ItemId

答案 2 :(得分:2)

SELECT a.itemid
       , count(a.itemid) as [count]
       , ((cast(count(a.itemid) as decimal) / t.total) * 100) as percentage
FROM table1 as a
INNER JOIN (SELECT count(*) as total FROM table1) as t ON (1=1)
GROUP BY a.item_id, t.total
ORDER BY a.item_id

答案 3 :(得分:0)

SELECT a.itemid, 
    count(a,itemid) as [count], 
    100.00 * (count(a.itemid)/(Select sum(count(*) FROM myTable)) as [Percentage]
 FROM myTable
    Group by a.itemid 
    Order by a.itemid