here is an example of my two table.
PROBLEM: How can I create SQL Query using left join?
HERE IS THE SCENARIO
As I've said earlier, I have two table (TABLE1 and TABLE2), I tried to use left join so that i can combine both UserID in one table
so here is the code
select * from table1 a left join table2 on a.userid = b.userid
so two tables are now combined.
what i need to do is this:
if the status is all complete then 'complete'
then if status contains complete and incomplete then 'incomplete'
else 'no status'
it should be look like this.
NOTE:
since UserID = 1 (table1) contains complete and incomplete status (table2)
then it display 'incomplete' (new column)
since UserID = 4 (table1) contains all complete status (table 2)
then it display 'completed' (new column)
WHAT IF I CHANGE THE STATUS TO INTEGER?
same procedure. thanks
There are plenty of ways to resolve for this: a subquery with a CASE statement in the join statement for the table you are joining in, a CASE statement in a temp table where all values are changed to match, or this handy little trick of using a CASE statement in the JOIN's ON clause.
The LEFT JOIN condition is used to decide how to retrieve rows from table 2nd_table. If there is a row in 1st_table that matches the WHERE clause, but there is no row in 2nd_table that matches the ON condition, an extra 2nd_table row is generated with all columns set to NULL.
An SQL Join is an operation that combines records from two or more tables. This is done by matching keys between tables.
In SQL Server, joins are case-insensitive.
SELECT a.*,
CASE WHEN b.totalCount = 1 AND b.totalINC = 0 THEN 'Complete'
WHEN totalCount IS NULL THEN ''
ELSE 'Incomplete'
END STatus
FROM table1 a
LEFT JOIN
(
SELECT UserID,
COUNT(DISTINCT STATUS) totalCount,
SUM(CASE WHEN status = 'Incomplete' THEN 1 ELSE 0 END) totalINC
FROM table2
GROUP BY UserID
) b ON a.UserID = b.UserID
UPDATE 1
the only thing you'll change is the CASE
SELECT a.*,
CASE WHEN b.totalCount = 1 AND b.totalINC = 0 THEN 'Complete'
WHEN totalCount IS NULL THEN ''
ELSE 'Incomplete'
END STatus
FROM table1 a
LEFT JOIN
(
SELECT UserID,
COUNT(DISTINCT STATUS) totalCount,
SUM(CASE WHEN status <> 100 THEN 1 ELSE 0 END) totalINC
FROM table2
GROUP BY UserID
) b ON a.UserID = b.UserID;
Easy, but tricky solution :
as INCOMPLETE is greater (for a db) than COMPLETE, you can simply do
SELECT a.UserID,
LOWER(COALESCE(MAX(b.status) , 'NO STATUS'))
FROM table1 a
LEFT JOIN table2 b on a.userid = b.userid
GROUP BY a.UserID
SqlFiddle (with Andomar's better solution as well)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With