我需要平均一个字符而不是整数的列。例如,客户从我的公司...电话和互联网订购两种方式。我被要求获得所有订单的百分比。
Cust | OrderType
-----------------
A | Phone
A | Phone
A | Phone
A | Internet
B | Internet
B | Internet
B | Phone
我如何提取这些数据并向我的经理表明,客户A 80%的时间通过电话订购,20%的时间通过互联网订购,客户B通过电话订购66%的时间和33%的互联网时间?
答案 0 :(得分:0)
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
答案 1 :(得分:0)
您基本上希望订单总数除以每种订单的数量。
/*
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
答案 2 :(得分:0)
尝试下面的这个SQL
数据示例(此数据保存在临时表@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
结果:
Cust OrderType Percentage
----- -------------------------------------------------- ----------------------
A internet 25
A Phone 75
B internet 75
B Phone 25
注意:创建@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')