这是我的数据库表:

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

我想要的输出:
Status   |  Total  | Percent
-------------------------------
Active   |    2    |  33.33
Inactive |    1    |  16.66
Removed  |    3    |  50
Total    |    6    |  100

我尝试过的:
SELECT
    OrderStatus AS Status,
    COUNT(OrderStatus) AS Total,
    ROUND(((COUNT(OrderStatus ) * 100)/COUNT(*)),2) AS Percent
FROM
    myTable

由于显而易见的原因,我的查询不起作用,任何帮助表示赞赏!

最佳答案

您缺少 group by 子句,您需要除以记录总数,这可以通过子查询获得:

SELECT
    OrderStatus AS Status,
    COUNT(OrderStatus) AS Total,
    ROUND((COUNT(OrderStatus ) * 100)/(select COUNT(*) from myTable),2) AS [Percent]
FROM
    myTable
Group by OrderStatus

关于sql - 循环遍历行并根据表名计数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34443239/

10-12 06:45