[英]SQL QUERY using LEFT JOIN and CASE Statement
here is an example of my two table. 这是我的两张桌子的一个例子。
PROBLEM: How can I create SQL Query using left join? 问题:如何使用左连接创建SQL查询?
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 正如我之前所说,我有两个表(TABLE1和TABLE2),我尝试使用左连接,以便我可以在一个表中组合两个UserID
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) 因为UserID = 1 (table1)包含完整和不完整的状态(table2)
then it display 'incomplete' (new column) 然后显示'不完整' (新栏目)
since UserID = 4 (table1) contains all complete status (table 2) 因为UserID = 4 (table1)包含所有完整状态(表2)
then it display 'completed' (new column) 然后显示'已完成' (新栏目)
WHAT IF I CHANGE THE STATUS TO INTEGER? 如果我将状态更改为INTEGER怎么办?
same procedure. 同样的程序。 thanks 谢谢
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 更新1
the only thing you'll change is the CASE
你唯一要改变的就是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 因为INCOMPLETE比COMPLETE更大(对于数据库),你可以做到
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) SqlFiddle (还有Andomar的更好的解决方案)
select a.UserID
, case
when sum(case when b.status = 'Incomplete' then 1 end) > 0
then 'Incomplete'
when sum(case when b.status = 'Complete' then 1 end) > 0
then 'Complete'
else 'No Status'
end
from table1 a
left join
table2 b
on a.userid = b.userid
group by
a.UserID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.