循环遍历行并根据表名进行计数

时间:2015-12-23 20:30:39

标签: sql ms-access

这是我的数据库表:

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

由于显而易见的原因,我的查询无效,任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:3)

你错过了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

答案 1 :(得分:0)

将表中的总记录分配给变量。这将防止需要为每条记录重新计算它。只有5条记录的小问题,但如果您将此逻辑应用于具有更多唯一值的更大表,则差异应该变得显着。

<强> SQL:

declare @TempTable table([OrderStatus] varchar(50))

insert into @TempTable
values
('Active'),
('Active'),
('Inactive'),
('Removed'),
('Removed')

DECLARE @TotalRecords int = (Select Count(*) from @TempTable)

SELECT
    OrderStatus AS Status,
    COUNT(OrderStatus) AS Total,
    ROUND((COUNT(OrderStatus ) * 100)/@TotalRecords,2) AS [Percent]
FROM
    @TempTable
Group by OrderStatus

<强>结果:

(5 row(s) affected)
Status                                             Total       Percent
-------------------------------------------------- ----------- -----------
Active                                             2           40
Inactive                                           1           20
Removed                                            2           40

(3 row(s) affected)