Skip to content
Advertisement

How to create a view using data from two tables

I have two tables

ITEM

  • id (int),
  • model (varchar),
  • weight (float),
  • fk_type (int)

TYPE

  • id (int),
  • name (varchar)

And I want to create a view with

  • TypeName (for every type name) –> varchar
  • NumberOfItems (total number of ITEMS for TypeName) —> int
  • NumberOfModels (total number of MODELS for TypeName) —> int
  • TotWeight (again sum of all the ITEMS weight per TypeName) —>float

For example: I have three pencils, two of them have the same model, and one rubber. I’m expecting to get something like this.

TypeName NumberOfItems NumberOfModels TotWeight
pencil 3 2 50
rubber 1 1 25

I tried something like this but I can’t get my head around it

SELECT 
    Type.Name,
    (SELECT DISTINCT COUNT(Item.fk_Type) FROM Item GROUP BY  Item.fk_Type) NumberOfItems, 
    (SELECT COUNT(Item.Model) FROM Item,Type WHERE Item.fk_Type = Type.Id)NumberOfModels ,
    (SELECT SUM(Item.Weight) FROM Item,Type WHERE Item.fk_Type = Type.Id)TotWeight
FROM 
    Item, Type 
GROUP BY 
    Type.Name 

Can someone help?

Advertisement

Answer

This is basically an aggregation query with a join:

select t.name, count(i.id) as num_items,
       count(distinct i.model) as num_models,
       sum(i.weight) as total_weight
from type t left join
     item i
     on i.fk_type = t.id
group by t.name;
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement