MySQL数据库中如何解决分组统计的问题_MySQL
-------------------------------- A | B | C | D a b | a c | a d | d e 1 1 | 1 1 | 1 A | A 1 2 2 | 1 3 | 2 B | B 2 3 4 | 1 4 | 3 C | C 3 4 6 | 2 1 | 4 D | D 4 --------------------------------
下面我们需要用一条sql语句将A表所有的列,B表对与A表a字段相关联的列求count,通过C表,将D表与A表关联起来,得到的结果如下:
1 1 3 1 2 2 1 2 3 4 0 3 4 6 0 4
Mysql语句解决:
select A.a,A.b,IFNULL(c,0) as c,D.a from (select 1 as a,2 as b union allselect 2 as a,2 as b union allselect 3 as a,4 as b union allselect 4 as a,6 as b) as A left outer join (select a,count(a) as c from(select 1 as a,3 as c union allselect 1 as a,3 as c union allselect 1 as a,3 as c union allselect 2 as a,3 as c ) B group by a) as Bon A.a=B.a join (select 1 as a,'A' as d union allselect 2 as a,'B' as d union allselect 3 as a,'C' as d union allselect 4 as a,'D' as d ) as C on A.a=C.a join(select 1 as a,'A' as d union allselect 2 as a,'B' as d union allselect 3 as a,'C' as d union allselect 4 as a,'D' as d ) as Don D.d=C.d
推荐阅读
-
解决mysql本地数据库不能用ip访问的问题
-
使用wordpress的$wpdb类读mysql数据库做ajax时出现的问题该如何解决
-
解决python写入mysql中datetime类型遇到的问题
-
MySQL 5.7中如何定位DDL被阻塞的问题
-
解决MySQL 5.7中定位DDL被阻塞的问题
-
解决Mysql5.7中文乱码的问题
-
解决mysql中只能通过localhost访问不能通过ip访问的问题
-
mysql数据库ERROR#1442报错问题的解决方法
-
Python中LOADDATAINFILE语句导入数据到MySQL遇到问题的解决方案分享
-
解决mysql创建数据库后出现:Access denied for user 'root'@'%' to database 'xxx'的问题