Learn From - Interactive SQL



INNER JOIN and Case statement.


You can use INNER JOIN and Case statement to split a column into two.

Below is shown the "Product" table:

ProductID ProductDesc StockQuantity ProductPrice
Prd001 DVD Player 23 85.50
Prd002 Mobile Phone 45 70.33
Prd003 Laptop 15 250.45
Prd004 Watch 42 33.45
Prd005 Camera 34 95.75

Below is shown the "ProductDeliveryTBL" table:

CustomerName ProductID DateOfDelivery DeliveryStatus
Aria Cruz Prd003 3/21/2011 12:00:00 AM NotDelivered
Elizabeth Brown Prd002 9/23/2011 12:00:00 AM Delivered
Maria Larsson Prd005 9/12/2010 12:00:00 AM NotDelivered
Martín Sommer Prd001 7/27/2009 12:00:00 AM Delivered
Peter Franken Prd002 9/3/2010 12:00:00 AM Delivered
Thomas Hardy Prd005 6/13/2009 12:00:00 AM Delivered
Yang Wang Prd005 8/21/2011 12:00:00 AM Delivered

SQL using INNER JOIN and Case statement


In the "Product" table, different products are listed. In "ProductDeliveryTBL" table, delivery status and the buyer names are listed.

Here in the "ProductDeliveryTBL" table, the column DeliveryStatus contains only two values "Delivered" and "Not Delivered". Using the Case statement we can split the DeliveryStatus column into "Delivered" and "Not Delivered" columns.

Select ProductID,
(Case when DeliveryStatus = 'Delivered' then 1 else 0 end) as Delivered_Count,
(Case when DeliveryStatus = 'NotDelivered' then 1 else 0 end) as NotDelivered_Count
From ProductDeliveryTBL

Note: The DeliveryStatus column is now split as "Delivered_Count" and "NotDelivered_Count" columns.

Above Query Executed Result:

ProductID Delivered_Count NotDelivered_Count
Prd003 0 1
Prd002 1 0
Prd005 0 1
Prd001 1 0
Prd002 1 0
Prd005 1 0
Prd005 1 0

In the SQL Query shown below the above query is used as a table with alias "tbl" in the From clause.

We can use this SQL Query shown below to know the "Delivered" and "NotDelivered" status of the products from the "ProductDeliveryTBL" table.

Text Editor below has the SQL Query, click the "View Result" button, to see the result.

Select tbl.ProductID, P.ProductDesc,
SUM(tbl.Delivered_Count) as Delivered,
SUM(tbl.NotDelivered_Count) as NotDelivered
From
(
     Select ProductID,
     (Case when DeliveryStatus = 'Delivered' then 1 else 0 end) as Delivered_Count,
     (Case when DeliveryStatus = 'NotDelivered' then 1 else 0 end) as NotDelivered_Count
     From ProductDeliveryTBL
) as tbl
INNER JOIN Product as P on tbl.ProductID = P.ProductID
GROUP BY tbl.ProductID, P.ProductDesc
ORDER BY tbl.ProductID;

Note: The From clause uses the SUBQUERY that acts as a table with alias name "tbl". In the SUBQUERY, Case Statements are used to seperate the "Delivered" and "NotDelivered" Products.
Inner Join is used to join both the tables using Primary Key ProductID column from the "Product" Table and Foreign Key ProductID column from the "ProductDeliveryTBL" table. Finally GROUP BY clause is used to get the sum of "Delivered" and "NotDelivered" Products.

SQL in Text Editor: