SQL Server Calculate Percentage in Table [duplicate]

c0vxltue  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(91)

This question already has answers here:

SQL Server, division returns zero (7 answers)
Closed 29 days ago.

I am trying to add a percentage column to my table but my results are funky with the sql below:

update code_data
set code_red_percent = case when red_code_count = 0 then 0
                            else (red_code_count / total_code_count) * 100
                       end

It seems to be populating by percent column with 100 any time that the total_code_count and red_code_count match, but any time that the numbers are different it updates the percent column to a 0. What am I missing here?

mum43rcc

mum43rcc1#

Looks like you are hitting integer division; multiply first:

update code_data set
  code_red_percent =
    case 
      when red_code_count = 0 then 0
      else 100 * red_code_count / total_code_count
    end
yqyhoc1h

yqyhoc1h2#

DECLARE @Table TABLE (code_red_count INT, total_code_count INT, code_red_percent AS (CAST(code_red_count AS DECIMAL(10,2))/CAST(total_code_count AS DECIMAL(10,2))), code_red_percent_upd DECIMAL(10,2));
INSERT INTO @Table (code_red_count, total_code_count) VALUES
(1, 10), (2, 10), (3, 10), (50,10);

SELECT *, code_red_count/total_code_count AS code_red_percent_int, CAST(code_red_count AS DECIMAL(10,2))/CAST(total_code_count AS DECIMAL(10,2)) AS code_red_percent_dec
  FROM @Table;

UPDATE @Table
  SET code_red_percent_upd = CAST(code_red_count AS DECIMAL(10,2))/CAST(total_code_count AS DECIMAL(10,2));

SELECT *
  FROM @Table;

First, we create a table and populate it with some example data (it's helpful if you provide this when asking a question).

The first SELECT shows two calculations. The first using INT values and the second DECIMAL values. You can see the INT values are returned as a rounded INT . The DECIMAL values return the expected result.

We can use the same method to perform the UPDATE if that's what you really want.

In the initial table definition I also included another column without a data type, instead providing a definition for the calculation required to get the value. This is pretty much the same as the calculation used in the select, except it's automatically handled by the engine, and will always be up to date if the values it's derived from ever change. This is a computed column: https://learn.microsoft.com/en-us/sql/relational-databases/tables/specify-computed-columns-in-a-table?view=sql-server-ver16
| code_red_count | total_code_count | code_red_percent | code_red_percent_upd |
| ------------ | ------------ | ------------ | ------------ |
| 1 | 10 | 0.1000000000000 | 0.10 |
| 2 | 10 | 0.2000000000000 | 0.20 |
| 3 | 10 | 0.3000000000000 | 0.30 |
| 50 | 10 | 5.0000000000000 | 5.00 |

相关问题