I have a very complicated mySQL query I want to run, and I am having trouble thinking of how to write it.
Basically I have three tables:
a(aID, name);
b(bID, val);
ab(aID, bID, include)
What I want to do is create a query that creates a table like this:
c(aID, percentage);
I want percentage to be (total/possible) in this way. Total is calculated like this. Everytime an a row and b row have a relation AND include is 1 I want total to add the value of b.val. Possible will be the sum of b.val except where ab.include = 0
For example:
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 |
+-----+------------+
Currently I have this:
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
This gives the percentage aID is paired with bID with respect to weight, but I wanted to add this other calculation.
Is this possible?
Tried this but it didn't work:
I was about to try this:
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