开发者

Get count percent of a record in a single query

开发者 https://www.devze.com 2023-04-03 14:17 出处:网络
refer to this question: Get count of items and their values in one column how I can get percent of record count in single query like this:

refer to this question:

Get count of items and their values in one column

how I can get percent of record count in single query like this:

ItemId        count          Percen开发者_Go百科t
------------------------------------
   1            2              33.3
   2            0                0
   3            1              16.6
   4            3              50.0            

thanks


COUNT(*) OVER() gives you the total count.

Edit But actually you need SUM(COUNT(MyTbl.ItemID)) OVER() as you are summing the values in that column.

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
    ItemId,
    count(*) as count,
    cast(count(*) as decimal) / (select count(*) from myTable) as Percent 
from myTable
group by 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
0

精彩评论

暂无评论...
验证码 换一张
取 消