Question

I am needing to average a column that is characters and not integers. For example clients order two ways from my company...phone and internet. I am being asked to get a percentage of how they all order.

Cust |  OrderType
-----------------
A    |  Phone
A    |  Phone
A    |  Phone
A    |  Internet
B    |  Internet
B    |  Internet
B    |  Phone

How can I pull this data and show my managers that Customer A orders by phone 80% of the time and Internet 20% of the time and Customer B orders by phone 66% of the time and Internet 33% of the time?

Was it helpful?

Solution

SELECT Cust,
SUM(CASE WHEN OrderType = 'Phone' THEN 1 ELSE 0 END) * 100 / COUNT(*)  'Phone percentage',
SUM(CASE WHEN OrderType = 'Phone' THEN 0 ELSE 1 END) * 100 / COUNT(*) 'Internet percentage'
FROM Table1 
GROUP BY Cust

OTHER TIPS

You basically want the total number of orders divided by the count of each type of order.

/*
create table #tmp (Cust CHAR(1), OrderType VARCHAR(10))

INSERT #tmp VALUES ('A', 'Phone')
INSERT #tmp VALUES ('A', 'Phone')
INSERT #tmp VALUES ('A', 'Phone')
INSERT #tmp VALUES ('A', 'Internet')
INSERT #tmp VALUES ('B', 'Internet')
INSERT #tmp VALUES ('B', 'Internet')
INSERT #tmp VALUES ('B', 'Phone')
*/

SELECT
     Cust, 
     OrderType, 
     (1.0 * COUNT(*)) / (SELECT COUNT(*) FROM #tmp t2 WHERE t2.Cust = t.Cust) pct,
     cast(cast(((1.0 * COUNT(*)) / (SELECT COUNT(*) FROM #tmp t2 WHERE t2.Cust = t.Cust) ) * 100 as int) as varchar) + '%' /* Formatted as a percent */
FROM #tmp t
GROUP BY Cust, OrderType

Try This sql below

Data Example (this data is kept in a temporary table @temp)

Cust  OrderType
----- --------------------------------------------------
A     Phone
A     Phone
A     Phone
A     internet
B     internet
B     internet
B     internet
B     Phone

SQl:

select Cust, OrderType, count(orderType)as float)*100/cast((select count(cust) 
from @temp where cust= a.cust) as Percentage from @temp a
group by cust,OrderType  

Result:

Cust  OrderType                                          Percentage
----- -------------------------------------------------- ----------------------
A     internet                                           25
A     Phone                                              75
B     internet                                           75
B     Phone                                              25

Note: To Create @temp

Declare @temp table
(
 Cust nvarchar(5),
 OrderType nvarchar(50)
)

insert into @temp values
('A','Phone'),
('A','Phone'),
('A','Phone'),
('A','internet'),
('B','internet'),
('B','internet'),
('B','internet'),
('B','Phone')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top