Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select percentage of rows that have a certain value - SQL

Tags:

sql

count

Say I have a table like this in Sequel Pro:

SaleID    VendorID
1             A
2             C
3             E
4             C
5             D

And I want to find the percentage of sales in which Vendor C was the vendor. (Obviously in this case it is 40%, but I'm working with much bigger tables). How would I do that? I was thinking something using the Count function, but I'm not sure how I would do it exactly. Thanks!

like image 446
japem Avatar asked Jun 12 '14 18:06

japem


People also ask

How do I select a percentage record in SQL?

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.

What is %s in SQL query?

The SQL LIKE Operator There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

How do you find percentiles in SQL?

PERCENT_RANK() The PERCENT_RANK function in SQL Server calculates the relative rank SQL Percentile of each row. It always returns values greater than 0, and the highest value is 1.

How do I select only certain rows in SQL?

Selection symbols to narrow row selection To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols.


1 Answers

select sum(case when vendorID = 'C' then 1 else 0 end) * 100 / count(*)
from your_table
like image 98
juergen d Avatar answered Sep 17 '22 14:09

juergen d