好的,较早的主题略有变化。使用相同的基本思想,我想获得字段的独立计数,然后我希望它们按更高阶的细分进行分组。
我扩展了 David 的示例以包含一个更高阶的列:
district_id, product_id, service_id
dist proj serv
1 1 1
1 1 2
1 1 2
1 1 3
1 1 3
1 1 4
1 2 2
1 2 4
1 2 4
1 2 5
1 2 5
2 1 1
2 2 1
2 1 6
2 2 6
2 3 6
为了得到总数的结果,我使用了一个带有两个子查询的简单查询。
select
(select count(Distinct project_id) from GroupAndCountTest) AS "projects",
(select count(Distinct service_id) from GroupAndCountTest) as "services";
projects services
3 6
挑战在于将其分组到 District_id 中。我想要的是:
district_id projects services
1 2 5
2 3 6
我最终使用了类似的子查询,但我能够组合它们的唯一方法(使用存储函数除外)是为每个地区重新运行子查询。(这不是一个大问题,但在我的应用程序中,子查询使用具有大量“区域”的多个表,因此对于每个“区域”再次运行两个子查询,这将变得越来越低效。
这个查询有效,但我希望看到更有效的东西。
select t1.district_id, p1.projects, s1.services
from GroupAndCountTest as t1
join (select district_id, count(Distinct project_id) as projects
from GroupAndCountTest
group by district_id) AS p1
on p1.district_id=t1.district_id
join (select district_id, count(Distinct service_id) as services
from GroupAndCountTest
group by district_id) as s1
on s1.district_id=t1.district_id
group by t1.district_id;
谢谢。
PS:如果您想进行实验,可以使用以下命令创建表:
CREATE TABLE `GroupAndCountTest` (
`district_id` int(5) DEFAULT NULL,
`project_id` int(5) DEFAULT NULL,
`service_id` int(5) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
insert into `GroupAndCountTest`(`district_id`,`project_id`,`service_id`)
values (1,1,1),(1,1,2),(1,1,2),(1,1,3),(1,1,3),(1,1,4),(1,2,2),(1,2,4),
(1,2,4),(1,2,5),(1,2,5),(2,1,1),(2,2,1),(2,1,6),(2,2,6),(2,3,6);