[英]Using COUNT and GROUP BY with multiple JOIN tables
i want to JOIN
multiple table and need to COUNT
from multiple tables using GROUP BY
我想
JOIN
多个表,需要使用GROUP BY
从多个表中COUNT
the tables less like this 桌子不太像这样
table A 表A
a_id | name
------------
1 | john
2 | david
3 | anna
table B 表B
b_id | b_title
--------------
1 | b1
2 | b2
3 | b3
table C 表C
c_id | c_title | b_id
------------------------
1 | c1 | 2
2 | c2 | 3
3 | c3 | 1
4 | c4 | 1
table D 表D
d_id | d_title | c_id | a_id | cost
-----------------------------------
1 | d1 | 3 | 1 | 200
2 | d2 | 1 | 1 | 130
3 | d3 | 2 | 2 | 240
4 | d4 | 2 | 3 | 170
5 | d5 | 4 | 1 | 95
what i want is something like this 我想要的是这样的
name | COUNT(b_id) | COUNT(d_id) | SUM(cost)
--------------------------------------------
john | 2 | 3 | 425
david| 1 | 1 | 240
anna | 1 | 1 | 170
this is my query 这是我的查询
SELECT a.name, COUNT(d.d_id), SUM(cost)
FROM a INNER JOIN d ON a.a_id = d.a_id
GROUP BY a.a_id
I tried but I could not get the correct result of COUNT(b_id)
我尝试过,但无法获得
COUNT(b_id)
的正确结果
You want to count distinct b_id
: 您要计算不同的
b_id
:
SELECT
a.name,
COUNT(DISTINCT c.b_id),
COUNT(d.d_id),
SUM(d.cost)
FROM d
JOIN a ON a.a_id = d.a_id
JOIN c ON c.c_id = d.c_id
GROUP BY a.a_id;
Just add extra JOIN
to the table c
like this: 只需将额外的
JOIN
添加到表c
如下所示:
SELECT a.name, COUNT(d.d_id), COUNT(b_id), SUM(cost)
FROM a
INNER JOIN d ON a.a_id = d.a_id
INNER JOIN c ON c.b_id = d.c_id
GROUP BY a.a_id, a.name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.