MySQL:Group By&计数多个字段:REDUX

时间:2012-07-03 18:05:12

标签: mysql count group-by

好的,早期主题略有不同。使用相同的基本思想,我想获得字段的独立计数,然后我希望它们按更高阶的细分分组。

我扩展了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

面临的挑战是将其归入group_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);

3 个答案:

答案 0 :(得分:3)

select district_id, 
count(distinct(product_id)) projects, 
count(distinct(service_id)) services 
from MyTable group by district_id;

其中MyTable包含district_id, product_id, service_id

答案 1 :(得分:0)

你这样做比你需要的更难。您不需要子查询,只需要GROUP BY。

select district_id, count(distinct project_id), count(distinct service_id)
from GroupAndCountTest
group by district_id

答案 2 :(得分:0)

SELECT district_id, count( DISTINCT (
project_id
) ) projects, count( DISTINCT (
service_id
) ) services
FROM GroupAndCountTest
GROUP BY district_id

我已经进步了:(

相关问题