Как посчитать процент в sql
Перейти к содержимому

Как посчитать процент в sql

  • автор:

Как найти проценты значений в SQL?

Я использую следующий запрос, чтобы узнать процент выигрыша героя в играх:

Но это дает мне процент для ВСЕХ игр. И я хочу знать

percentage(for Hero)=(Won games by this player)/(Played games by this hero)

процент (для Героя) = (Выиграли игры этим игроком)/(Все игры)
Благодарю.

3 ответа

Используйте count(HERO) вместо count(*) поскольку я думаю, что он не может выполнить группу должным образом.

EDIT: Я считаю, вы хотели, чтобы sum of PointsEarned делилась на счет. В этом случае запрос немного изменится, как показано ниже:

Как рассчитать процент с помощью оператора SQL

У меня есть таблица SQL Server, которая содержит пользователей и их оценки. Для простоты скажем, что есть 2 столбца — name & grade . Таким образом, типичной строкой будет имя: «Джон Доу», оценка: «А».

Я ищу один оператор SQL, который найдет процентное соотношение всех возможных ответов. (A, B, C и т. Д.) Кроме того, есть ли способ сделать это без определения всех возможных ответов (открытое текстовое поле — пользователи могут ввести «прошел / не прошел», «нет» и т. Д.)

Окончательный результат, который я ищу: A: 5%, B: 15%, C: 40% и т. Д.

13 ответы

Я протестировал следующее, и это действительно работает. Ответ gordyii был близок, но в нем было умножение 100 не в том месте и отсутствовали некоторые скобки.

ответ дан 01 дек ’09, 17:12

это дает результат в виде целых чисел. сумма результатов не равна 100. — гром

Не самый эффективный, так как таблица будет сканироваться дважды. Кроме того, запрос не будет выглядеть так просто, если имеется более одной ссылки на таблицу. — Алекс Аза

@Thunder вы можете изменить 100 на 100.0 для десятичных значений. — Джозеф

Может ли кто-нибудь объяснить, почему математический синтаксис SQL-запроса — это не то, что вы ожидаете от обычного? Например нормально я бы разделил на общее количество раз на 100? Искренне любопытно на этот счет с логической точки зрения. — Digitalsa1nt

@ Digitalsa1nt (100 * 2) / 4 = 50, (2/4) * 100 = 50, пока перечислитель является умножаемой частью. Из-за приоритета операторов SQL он будет таким же. однако из-за типов данных при использовании 100 вы все равно можете получить результат, округленный до 0 десятичных знаков, который вы хотите для%, где, как если бы вы поместили его после операции деления, вам нужно будет убедиться, что вы приводите к типу данных, который может обрабатывать десятичные разряды, иначе вы получите 100 или 0, а не фактический процент — Мэтт

How to calculate percentage in SQL on Snowflake

Supercharge Your Snowflake SQL with Datameer's Data Transformation

There are different ways to calculate percentage in SQL like:

  • Using Ratio_to_report() function or the Percent_Rank function
  • Using OVER() clause
  • Using subquery
  • Using CTE

Calculating percentage in SQL

Let us consider the ‘inventory’ table as below. We can calculate the percentage of each item in the inventory.

Snowflake SQL

In Snowflake, you can use the Ratio_to_report() function or the Percent_Rank function, depending on your use case.

Keep Tabs on your “Calculated(%)” SQL Using Datameer’s Graphical Interface

Datameer is a collaborative, multi-persona data transformation platform that integrates with Snowflake.

With Datameer on Snowflake, you can use the SQL functions you’re familiar with to calculate your percentage and visually track all your calculated percentage queries with our low-code GUI interface.

To reap the benefits of these easy drag-and-drop modeling and self-documenting features, kickstart your Snowflake instance and connect your Datameer account.

SQL percentage calculation examples in SQL Server

Ben Richardson

In this article, you will see the different ways to calculate SQL percentage between multiple columns and rows. You will also see how to calculate SQL percentages for numeric columns, grouped by categorical columns. You will use subqueries, the OVER clause, and the common table expressions (CTE) to find SQL percentages.

So, let’s begin without any ado.

Finding Percentage using Two Variables

There is no built-in operator that calculates percentages in SQL Server. You have to rely on basic arithmetic operations i.e. (number1/number2 x 100) to find percentages in SQL Server.

Before finding the SQL percentages across rows and columns, let’s first see how you can find percentages using two basic variables in SQL Server.

The script below defines three float variables @num1, @num2 and @perc. Next, the @num2 variable is divided by the @num1 variable and the result is multiplied by 100 which is stored in the @perc variable and is printed on the console.

Output:

result of basic percentage

Finding Percentages Between Two Columns

Finding Percentages between two columns is straightforward. You can simply use the column names and the division operator “/” to divide values in one column by another. The result is a list of values that correspond to the result of the division of all the values in the two columns.

Let’s see an example.

The script below, creates a table Result with two float type columns “obtained”, and “total”. The script also inserts five dummy rows in the Result table. The SELECT query then selects all the records in the Result table. Here is an example:

Output:

percentages accross columns

Let’s try to find percentages for each row as a result of the division between the values in the “obtained” and “total” columns as shown below where a new column is added for percentages.

Result set

Finding Percentages via Subqueries

Finding SQL percentages between two columns is straightforward. However, the process is not as straightforward for finding percentages across rows for different scenarios.

Let’s first discuss a very simple scenario where you have to find what is the percentage of a value in a column among all the rows in the column.

The following script creates a table Scores with one column.

Output:

result of percentage via subquery

Now if you want to find what percent of the sum of total values in the “val” column does each value constitutes, you can use subqueries.

In this regard, the outer query will multiply all the values in the “val” column by 100 which will be divided by the result of the subquery which finds the sum of all the values in the “val” column.

Let’s first see how our subquery looks that calculate the sum of the values in the “val” column.

Output:

Output of SUM

The following script returns the percentage of the total for each value in the “val ” column.

percentage of total values using subqueries

If you do not want to exclude any value while calculating the percentage of the total, you can do so with the WHERE clause as shown in the script below where the value 40 is not included.

percentage of total values using subqueries with WHERE clause

You can see from the above output that the values now have a larger percentage share of total values since the value 40 is removed.

Finally, as a side note, you can round off the percentages returned using the “round” function as shown below. The script below rounds off the percentage values to 2 decimal places.

Output:

percentage of total values using subqueries with ROUND OFF

Let’s now see a real-world example of how you can calculate SQL percentage. You will be using the Northwind sample database which you can download and install from this link.

Run the following script to see the columns in the Products table.

Output:

Products table from Northwind database

The Products table contains columns that contain Supplier ID, Category ID, Unit Price and other information about the products in the Northwind database.

Consider a scenario where you have to find the percentage of the products supplied by each supplier. To find such percentage values, you need two values:

  1. The total number of all the products which you can get via the COUNT function
  2. The total number of products supplied for each supplier, which you can get using the GROUP BY function.

You can then multiply the 2 nd value (count of products grouped by supplier ids) by 100 and then divide the result by the 1 st value (total count of products).

Here is how you can use subqueries to find these such SQL percentages.

Output:

percentage of total products by suppliers

The above results show that the percentage of products supplied by each supplier. For instance, you can see that the supplier with id 1 supplied 3.89% of the total products.

USING Over Clause

The Over clause is an extremely useful Window function that calculates values over a range of values. You can use the Over clause to calculate SQL percentages as well. With the Over clause, you can avoid the use of subqueries for calculating percentages.

Let’s see an example. The script below finds the percentage of products supplied by every supplier. You can see that the following script is very similar to what you saw in the previous section. However, in this case, instead of using a subquery that returns the count of all products, we use the Over clause which returns the sum of all the products.

The output below is similar to what you achieved using a subquery.

Output:

result of calculating percentage using OVER clause

Let’s now see a more complex example of finding SQL percentages. Consider a scenario where for each supplier you want to calculate the percentage of unit price for all the products. In other words, you want to find out that what percentage of the sum of unit prices for all the products is being paid to a different supplier. You can do so with the help of the OVER clause as follows.

In the script below, the supplier ids are displayed along with the sum of unit prices paid to all suppliers, and the percentages of unit prices paid to all suppliers.

To calculate the sum of unit prices, the formula is simple, you can use the SUM function and pass it to the column containing the unit prices.

To calculate the percentages for unit prices, you need to multiply the sum of unit prices for each supplier by 100 and then divide the result with the total sum of unit prices for all the suppliers. In the script below, in the denominator, the SUM function is called twice. Since we are using the OVER operator, the first SUM function only adds the prices for each supplier. To find the sum of unit prices paid to all suppliers, another SUM function is called.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *