查询非常复杂,不确定是否可能。涉及不添加到运行总和

时间:2013-05-01 07:25:04

标签: mysql sql database

我想运行一个非常复杂的mySQL查询,而我在思考如何编写它时遇到了困难。

基本上我有三张桌子:

a(aID, name);
b(bID, val);
ab(aID, bID, include)

我想要做的是创建一个创建如下表格的查询:

c(aID, percentage);

我希望以这种方式获得百分比(总计/可能)。总计是这样计算的。每次一行和一行有一个关系AND include是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

1 个答案:

答案 0 :(得分:4)

试试这个(sqlfiddle):

SELECT ab.aID, SUM(b.val*ab.include)/(possible.possible-SUM((1-ab.include)*b.val))*100 AS percentage
FROM ab, b, (SELECT SUM(val) possible FROM b) possible
WHERE ab.bID = b.bID
GROUP BY ab.aID

numerator(total):将我们有关系的所有b值相加

分母(可能):从所有b值的总和中扣除存在关系的值且包含为0。