8

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          Percent
------------------------------------
   1            2              33.3
   2            0                0
   3            1              16.6
   4            3              50.0            

thanks

Community
  • 1
  • 1
Arian
  • 12,793
  • 66
  • 176
  • 300
  • Something like the solution in this [SO post](http://stackoverflow.com/questions/770579/how-to-calculate-percentage-with-a-sql-statement) should help you calculate the percentage. – JW8 Sep 07 '11 at 20:42

4 Answers4

13

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  
Martin Smith
  • 438,706
  • 87
  • 741
  • 845
4
select
    ItemId,
    count(*) as count,
    cast(count(*) as decimal) / (select count(*) from myTable) as Percent 
from myTable
group by ItemId
Kuyenda
  • 4,529
  • 11
  • 46
  • 64
Adam Dymitruk
  • 124,556
  • 26
  • 146
  • 141
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
Kuyenda
  • 4,529
  • 11
  • 46
  • 64
Johan
  • 74,508
  • 24
  • 191
  • 319
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
Pang
  • 9,564
  • 146
  • 81
  • 122