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

Sql 获取单个查询中记录的计数百分比,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,关于这个问题: 如何在单个查询中获得记录计数的百分比,如下所示: ItemId count Percent ------------------------------------ 1 2 33.3 2 0 0 3 1 16.6 4 3 50.0

关于这个问题:

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

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

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

select
    ItemId,
    count(*) as count,
    cast(count(*) as decimal) / (select count(*) from myTable) as Percent 
from myTable
group by ItemId
编辑但实际上,在对该列中的值求和时,您需要在()上求和(COUNT(COUNT(MyTbl.ItemID))

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  

类似于此的解决方案可以帮助您计算百分比。
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
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