sql - SUM Two Different Columns in two different tables Grouped by Column in third table -
i can work in 2 seperate queries can't both joins have 3 columns. can me out please? need output this:
+------------------------------------------------+ | cluster_name | total_units |allocated_units| +------------------------------------------------+ | cluster1 | 300 |25 | +------------------------------------------------+ | cluster2 | 400 |45 | +------------------------------------------- ----+
two seperate queries working:
query 1:
select cluster_info.cluster_name, sum(host_info.unit_count) 'total_units' cluster_info inner join host_info on host_info.cluster_id = cluster_info.cluster_id group cluster_info.cluster_name
query 2:
select cluster_info.cluster_name, sum(vm_info.unit_count) 'allocated_units' cluster_info inner join vm_info on cluster_info.cluster_id = vm_info.cluster_id group cluster_info.cluster_name
table 1 (cluster_info):
+--------------------------------+ | cluster_name | cluster_id | +--------------------------------+ | cluster1 | 1 | +--------------------------------+ | cluster2 | 2 | +--------------------------------+
table 2 (host_info):
+------------------------------------------------+ | host_name | cluster_id | unit_count | +------------------------------------------------+ | host1 | 1 | 150 | +------------------------------------------------+ | host2 | 1 | 150 | +------------------------------------------------+ | host3 | 2 | 200 | +------------------------------------------------+ | host4 | 2 | 200 | +------------------------------------------------+
table 3 (vm_info):
+------------------------------------------------+ | vm_name | cluster_id | unit_count | +------------------------------------------------+ | vm1 | 1 | 10 | +------------------------------------------------+ | vm2 | 1 | 15 | +------------------------------------------------+ | vm3 | 2 | 20 | +------------------------------------------------+ | vm4 | 2 | 25 | +------------------------------------------------+
it safest using 2 subqueries:
select ci.cluster_name, hi.total_units, vi.allocated_units cluster_info ci left join (select hi.cluster_id, sum(hi.unit_count) total_units host_info hi group hi.cluster_id ) hi on ci.cluster_id = hi.cluster_id left join (select vi.cluster_id, sum(vi.unit_count) allocated_units vm_info vi group vi.cluster_id ) vi on ci.cluster_id = vi.cluster_id ;
i introduced table aliases make query more readable. and, don't put column aliases in single quotes. don't need quote these names @ all. use single quotes date , string constants.
this sql fiddle shows working.
Comments
Post a Comment