Using COUNT and Return Percentage Against SUM of Records

假如想象 提交于 2020-01-06 21:38:48

问题


Pretty simple question I suppose, but I can't find the answer on here!

I am trying to calculate the volume of records based on a WHERE clause, as well as return a percentage of those records based on the same where clause. The percentage would be calculated against the total amount of records in the database. For example, I count all my records that meet "MyCondition":

SELECT COUNT(*) FROM [MyTable]     
WHERE Condition='MyCondition'

This works fine. However, how does one take that count, and return the percentage it equates to when put against all the records in the database? In other words, I want to see the percentage of how many records meet WHERE Condition='MyCondition' in regards to the total record count.

Sorry for the simple question and TIA! I am using MS SQL 2012.


回答1:


You can do simply divide the match of the count by the total number of records.

Sample Data:

create table test (MatchColumn int)

insert into test (MatchColumn)
values (1),(1),(1),(2),(3),(4)

Match Condition:

SELECT COUNT(*) MatchValues, 
      (SELECT COUNT(*) FROM test) TotalRecords,
      CAST(COUNT(*) AS FLOAT)/CAST((SELECT COUNT(*) FROM test) AS FLOAT)*100 Percentage
FROM [test]     
WHERE MatchColumn=1

Returns:

| MATCHVALUES | TOTALRECORDS | PERCENTAGE |
|-------------|--------------|------------|
|           3 |            6 |         50 |

SQL Fiddle Demo

Using a CTE:

Another option is to do the same with a CTE and reference the columns it creates:

;WITH CTE AS 
  (SELECT COUNT(*) MatchValues, 
      (SELECT COUNT(*) FROM test) TotalRecords      
   FROM [test]     
   WHERE MatchColumn=1)
SELECT MatchValues, TotalRecords, 
       CAST(MatchValues AS FLOAT)/CAST(TotalRecords AS FLOAT)*100 Percentage
FROM CTE

SQL Fiddle Demo

NOTE: Casting the counts to a float to calculate a percentage is required as dividing 2 int values would return an int, but in this case we want a decimal value less than 0, which would simply be 0 if it were an int.

Reference:

SQL Server, division returns zero




回答2:


Here is another method that only hits the base table once.

SELECT COUNT(*) as TotalCount
    ,SUM(case when Condition = 'MyCondition' then 1 else 0 end) as ConditionalCount
FROM [MyTable]     



回答3:


Or something like this.

create table test (MatchColumn int)
insert into test (MatchColumn)
values (1),(1),(1),(2),(3),(4)

SELECT
(SELECT COUNT(*) FROM test WHERE MatchColumn=1) MatchValues, 
(SELECT COUNT(*) FROM test) TotalRecords,
((SELECT CAST(COUNT(*) AS FLOAT) FROM test WHERE MatchColumn=1)/CAST((SELECT COUNT(*) FROM test) AS FLOAT)*100) Percentage


来源:https://stackoverflow.com/questions/25288997/using-count-and-return-percentage-against-sum-of-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!