Home > OS >  Using Table 1 as Title column and Table 2 as Content columns
Using Table 1 as Title column and Table 2 as Content columns

Time:05-19

I have two tables:

Table 1: Category Table

CatCode CatDesc Total
CAT0001 Drinks 22
CAT0002 Food 12

Table 2: Product Table

ProdCode ProdDesc Amount CatCode
P00001 Coke 10 CAT0001
P00002 Pepsi 12 CAT0001
P00003 Burger 5 CAT0002
P00004 Fries 5 CAT0002
P00005 Eggs 2 CAT0002

I want to ask if it is possible to make a sql result where Table 1 contains the Category Code, Category Description, and Total but in the next column contains Table 2 which contains the Product Code, Product Name, and Quantity?

Expected outcome:

CAT0001 Drinks 22
P00001 Coke 10
P00002 Pepsi 12
CAT0002 Food 12
P00003 Burger 5
P00004 Fries 5
P00005 Eggs 2

CodePudding user response:

  1. Try this (tested on dbfiddle)
SELECT catcode as code, catdesc as name, total as amount
FROM (
  SELECT catcode, catdesc, total, catcode AS catcode2 FROM category
  UNION ALL
  SELECT prodcode, proddesc, amount, catcode AS catcode2 FROM product
) tmp
ORDER BY catcode2, catcode;
  • Related