简体   繁体   中英

sql Calculating a percentage for a group

iam trying to get this

1.select all the rows that [result] != Success

2.count each unique [result]

3.tell me how much % each [result] take from all [result]

seems like the first two works fine but the last column is always '0'

this is my query:

SELECT  [result] , COUNT( * ) AS Total,(
                                             COUNT( * ) / 
                                             ( 
                                              SELECT COUNT( * ) 
                                              FROM[my_table] 
                                             ) 
                                         ) * 100 AS  '%' 

                                         FROM [my_table]
                                            WHERE  ([result]!='Success') 
                                            GROUP BY  [result] 

this is the result:

在此处输入图片说明

tank you all!

You need to convert the numbers to decimals or floating point numbers, or you will be operating on integers.

SELECT  [result] , COUNT( * ) AS Total,
      (1.0 * COUNT( * ) / ( 
           SELECT COUNT( * ) 
           FROM[my_table] 
           ) 
      ) * 100 AS  '%' 
FROM [my_table]
WHERE  ([result]!='Success') 
GROUP BY  [result] 

I would try this:

  select [result], count(1) over (partition by [result]), 
  (count(1) over (partition by [result]) * 100/count(*))
  FROM [my_table]
  WHERE  ([result]!='Success') 

I think your code works though, I think you need to * 100 before you divide, I think you are finding an issue with using ints and having a value < 1, so it rounds to 0.

This should do it, as long as the first number is a float the result will be a float

  SELECT [result] 
  ,COUNT(*) AS Total
  ,CAST((COUNT(*)AS FLOAT) / (SELECT COUNT(*) FROM [my_table])) AS '%' 
  FROM [my_table]
  WHERE  ([result]!='Success') 
  GROUP BY  [result] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM