Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get count percent of a record in a single query

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

like image 887
Arian Avatar asked Sep 07 '11 20:09

Arian


People also ask

What is %s in SQL query?

%s is a placeholder used in functions like sprintf. Check the manual for other possible placeholders. $sql = sprintf($sql, "Test"); This would replace %s with the string "Test".

How do I get a count in SELECT query?

You can use the SQL SELECT statement with the COUNT() function to select and display the count of rows in a table of a database.


1 Answers

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  
like image 91
Martin Smith Avatar answered Sep 23 '22 00:09

Martin Smith