Marcx
Marcx

Reputation: 6836

SQL Select problem

I have a problem trying to figure out how to create a query... Let's assume we have 2 tables like these:

TABLE A
id - box1_id - box1count - box2_id - box2_count
1  - 1       - 100       - 2       - 111
2  - 2       - 222       - NULL    - NULL
3  - 2       - 333       - 3       - 1000

TABLE B
id_box - box_Name
1      - HELLO
2      - TEST
3      - HELP

I want to write a query that retrive something like that:

id_box - box_Name - box_sumcount
1      - HELLO    - 100
2      - TEST     - 666
3      - HELP     - 1000

box_sumcount is the sum of box1_count or box2_count based on box1_id or box2_id are equal to id_box...

Upvotes: 0

Views: 116

Answers (1)

JohnFx
JohnFx

Reputation: 34917

SELECT TableB.id_Box,TableB.Boxname, Sum(BC.BoxCount)
FROM TableB
INNER JOIN 
  (SELECT box1_id as boxid, box1Count as boxCount
   UNION 
   SELECT box2_id as boxid, box2Count as boxCount
  ) BC
 ON (TableB.id_box=BC.Boxid)
 GROUP BY TableB.id_Box, TableB.Boxname

Upvotes: 4

Related Questions