I have a table something like below
level1 | level2 | level3 | key |
---|---|---|---|
A | B | C | k1 |
A | B | C | K2 |
A | B | D | k2 |
A | B | E | k3 |
A | F | G | k4 |
A | F | null | k5 |
A | null | null | k6 |
A | B | null | k7 |
A | B | null | k8 |
I am expecting to carry hierarchy information to child count like below
A-->1
A-->B -->2+1(a)=3
A-->B--->C-->1+2+2( 2 entries for ABC)=5
A--B-->D-->1+2+1=4
A--B-->E-->1-->1+2+1=4
A--F-->1+1=2
A--F-->G-->1+1+1=3
My tried the query below does not give the right result
select CONCAT(ifnull(level1, ''), ' > ', ifnull(level2, ''), ' > ', ifnull(level3, '')) as 'foo',COUNT(*) as 'count' from table t t.level1, t.level2, t.level3;
How can I apply the aggregate function and fetch the right result.
2
Answers
This query gave me desired result:
dbfiddle demo
except for AFG which should be 3? (A once + AF once + AFG once).
Query groups values at first, then self joins all occurences
g3
with two occurencesg2
and one occurenceg1
and presents as requested.Try the following:
demo