Moons
Moons

Reputation: 3854

Query to get the percentage of orders placed by a customer

I have a Product table that has a column OrderStatusID.

Here's an example query:

SELECT * FROM dbo.Product where CustomerID = 10;

The problem: find the percentage of Products where OrderStatusID is not null.

Upvotes: 0

Views: 374

Answers (4)

Diego
Diego

Reputation: 36166

declare @total numeric(10,2)
select @total =count(*) from orders

select customerID, cast(100*count(*)/@total as numeric(10,2)) as Percentage
from orders
where customerID=10
group by customerID

Upvotes: 1

zon7
zon7

Reputation: 539

The simplest way is like this

SELECT 100*Count(OrderStatusID)/(SELECT count(*) FROM dbo.Product) FROM dbo.Product;

Hope it helps

Upvotes: 1

Lamak
Lamak

Reputation: 70668

SELECT CAST(COUNT(OrderStatus) AS FLOAT)/COUNT(*)*100 Percentage
FROM dbo.Product
WHERE CustomerID = 10

Upvotes: 1

Joe Phillips
Joe Phillips

Reputation: 51200

SELECT
    SUM(CASE WHEN CustomerID=10 THEN 1 ELSE 0 END) / COUNT(CustomerID)
    as Percentage
FROM dbo.Product

Upvotes: 0

Related Questions