我有一个非常复杂的 mySQL 查询,我想运行它,但我在思考如何编写它时遇到了麻烦。
基本上我有三个表:
a(aID, name);
b(bID, val);
ab(aID, bID, include)
我想要做的是创建一个创建这样的表的查询:
c(aID, percentage);
我希望以这种方式(总/可能)百分比。总计是这样计算的。每次 a 行和 b 行有关系并且包含为 1 我希望总计添加 b.val 的值。可能是 b.val 的总和,除非 ab.include = 0
例如:
a:
+-----+
| aID |
+-----|
| 1 |
| 2 |
| 3 |
+-----+
b:
+-----+-----+
| bID | val |
+-----+-----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
+-----+-----+
ab:
+-----+-----+---------+
| aID | bID | include |
+-----+-----+---------+
| 1 | 1 | 1 |
| 1 | 3 | 0 |
| 2 | 1 | 1 |
| 3 | 1 | 1 |
| 3 | 2 | 1 |
| 3 | 3 | 1 |
+-----+-----+---------+
c:
+-----+------------+
| aID | percentage |
+-----+------------+
| 1 | 50 |
| 2 | 33.33 |
| 3 | 100 |
+-----+------------+
目前我有这个:
SELECT a.aID, (SUM(b.val)/(SELECT SUM(val) FROM b))*100 AS percentage
FROM a, ab, b
WHERE a.aID = ab.aID AND ab.bID = b.bID
GROUP BY a.aID
这给出了 aID 与 bID 相对于重量的百分比,但我想添加其他计算。
这可能吗?
试过这个,但没有奏效:
我正要试试这个:
SELECT a.aID, (SUM(b.val)/(SELECT SUM(val) FROM b,ab WHERE ab.include = 1))*100 AS percentage
FROM a, ab, b
WHERE a.aID = ab.aID AND ab.bID = b.bID AND ab.include = 1
GROUP BY a.aID