Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through rows and count based on table name

Tags:

sql

ms-access

This is my database table:

Status
------
Active
Active
Inactive
Removed
Removed

My desired output:

Status   |  Total  | Percent
-------------------------------
Active   |    2    |  33.33   
Inactive |    1    |  16.66
Removed  |    3    |  50
Total    |    6    |  100

What i've attempted:

SELECT
    OrderStatus AS Status,
    COUNT(OrderStatus) AS Total,
    ROUND(((COUNT(OrderStatus ) * 100)/COUNT(*)),2) AS Percent
FROM
    myTable

For obvious reasons my query is not working, any help appreciated!

like image 966
Michael Bui Avatar asked Apr 13 '26 11:04

Michael Bui


1 Answers

You're missing the group by clause, and you need to divide by the total number of records, which you can get with a subquery:

SELECT
    OrderStatus AS Status,
    COUNT(OrderStatus) AS Total,
    ROUND((COUNT(OrderStatus ) * 100)/(select COUNT(*) from myTable),2) AS [Percent]
FROM
    myTable
Group by OrderStatus
like image 108
Brian Pressler Avatar answered Apr 16 '26 01:04

Brian Pressler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!