I'm trying to GROUP
, SORT
and COUNT
in a single query one of my table named 'commodities'.
Here is a simplification of my MySql
table :
family sub_family name detailed_name Agro Grains Wheat Wheat per 1 mt Agro Grains Corn Corn per 1 mt Agro Grains Sugar Sugar per 1 mt Agro Fruits Apple Apple red Agro Fruits Apple Apple green Agro Fruits Apple Apple yellow Agro Fruits Lemon Lemon classic Wood Tree Lemon Lemon in logs Wood Tree Oak Oak in logs Wood Tree Epicea Epicea in logs Wood Packaging Kraftliner Krafliner 3mm
I would like to :
GROUP
byname
SORT
byfamily
,sub_family
and lastlyname
COUNT
the numbers of rows for eachfamily
,sub_family
and thenname
(IN THE SAMEsub_family
)
So far I managed to do everything but COUNT
in the same sub_family
.
Indeed, the following query :
SELECT TableC.family, TableC.NbrFamily, TableB.sub_family, TableB.NbrSubFamily, TableA.name, TableA.NbrName FROM ( SELECT family, sub_family, name, COUNT(DISTINCT commodities.id) AS NbrName FROM commodities GROUP BY name ) TableA INNER JOIN ( SELECT sub_family, COUNT(DISTINCT commodities.id) AS NbrSubFamily FROM commodities GROUP BY sub_family ) TableB ON (TableA.sub_family = TableB.sub_family) INNER JOIN ( SELECT family, COUNT(DISTINCT commodities.id) AS NbrFamily FROM commodities GROUP BY family ) TableC ON (TableA.family = TableC.family) GROUP BY TableA.name ORDER BY TableA.family,TableA.sub_family,TableA.name
which results in the following :
family NbrFamily sub_family NbrSubFamily name NbrName Agro 7 Grains 3 Wheat 1 Agro 7 Grains 3 Corn 1 Agro 7 Grains 3 Sugar 1 Agro 7 Fruits 4 Apple 3 Agro 7 Fruits 4 Lemon 2 Wood 4 Tree 3 Lemon 2 Wood 4 Tree 3 Oak 1 Wood 4 Tree 3 Epicea 1 Wood 4 Packaging 1 Kraftliner 1
You can see that NbrName
counts Lemon 2 times but I would like it to count it only 1 time because one lemon is in Fruits sub_family
and the other in Tree sub_family
.
[UPDATE] : Here are my desired results :
family NbrFamily sub_family NbrSubFamily name NbrName Agro 7 Grains 3 Wheat 1 Agro 7 Grains 3 Corn 1 Agro 7 Grains 3 Sugar 1 Agro 7 Fruits 4 Apple 3 Agro 7 Fruits 4 Lemon 1 Wood 4 Tree 3 Lemon 1 Wood 4 Tree 3 Oak 1 Wood 4 Tree 3 Epicea 1 Wood 4 Packaging 1 Kraftliner 1