※ 引述《kafel0936 (je ne pense qu'a toi)》之铭言:
: 请问一下各位先进,
: 我用mysql,写 count(*)/(select count (*) from 资料来源) as percentage
: 如果我有不同群组要计算比例,要怎么分群?
: 我用group by,结果分母都是所有资料的数量,
: 我要的是分群数量为分母...
1. 先统计第一层的分组数量
2. 再统计第一层+第二层的分组数量
3. 将上述两个结果集 Join 在一起
以下例来说:
create table Lab0322
(
CustomerID int,
OrderDate char(10),
ProductID char(2),
OrderNo int
);
insert into Lab0322 values (1, '2012-01-05', 'AA', 1);
insert into Lab0322 values (2, '2012-01-05', 'AB', 1);
insert into Lab0322 values (3, '2012-01-05', 'AA', 1);
insert into Lab0322 values (3, '2012-01-10', 'DD', 1);
insert into Lab0322 values (2, '2012-01-10', 'AA', 1);
insert into Lab0322 values (1, '2012-01-15', 'AA', 1);
insert into Lab0322 values (2, '2012-01-15', 'AB', 1);
insert into Lab0322 values (3, '2012-01-15', 'AA', 1);
insert into Lab0322 values (3, '2012-01-15', 'DD', 1);
insert into Lab0322 values (1, '2012-01-20', 'AB', 1);
insert into Lab0322 values (2, '2012-01-20', 'DD', 1);
执行下列查询,列出的是各产品的销售次数:
select ProductID, count(*) GroupCount from Lab0322
group by ProductID
下列的查询,更进一步统计各产品与客户的销售次数:
select ProductID, CustomerID, count(*) SubGroupCount from Lab0322
group by ProductID, CustomerID
好了,将上述两个结果集,依照相同的产品编号 JOIN 在一起,
便可统计出各个客户在该品项的比例:
select R.ProductID, R.CustomerID, SubGroupCount,
SubGroupCount * 1.0 / GroupCount as Ratio
from (
select ProductID, count(*) GroupCount from Lab0322
group by ProductID
) L join (
select ProductID, CustomerID, count(*) SubGroupCount from Lab0322
group by ProductID, CustomerID
) R on R.ProductID = L.ProductID;