SQL QUERY using LEFT JOIN and CASE Statement
here is an example of my two tables.
Problem: How do I create a SQL query using a left join?
HERE IS THE SCENARIO
As I said before, I have two tables (TABLE1 and TABLE2), I tried to use a left join to combine both UserIDs in one table
so here is the code
select * from table1 a left join table2 on a.userid = b.userid
so the two tables are now merged.
what I need to do:
if the status is fully completed , then 'complete'
then if the status contains complete and incomplete , then "incomplete"
else 'no status'
it should look like this.
NOTE :
since UserID = 1 (table1) contains full and incomplete status (table2)
it displays "incomplete" (new column)
since UserID = 4 (table1) contains all full status (table 2)
then it displays "completed" (new column )
-----------------------------------
WHAT IF I CHANGE THE STATUS OF INTEGERA?
the same procedure. thank
source to share
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 change is 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;
source to share