这是我的两张桌子的一个例子。
问题: 如何使用左连接创建SQL查询?
这里是情景
正如我之前所说,我有两个表(TABLE1和TABLE2), 我尝试使用左连接,以便我可以组合两个UserID 在一个表中
所以这是代码
select * from table1 a left join table2 on a.userid = b.userid
现在合并了两个表。
我需要做的是:
如果状态全部完成则“完成”
然后,如果状态包含完整且不完整,则“不完整”
别的'没有地位'
它应该是这样的。
注意:
由于 UserID = 1 (table1)包含完整且不完整状态(table2)
然后显示'不完整'(新栏目)
由于 UserID = 4 (table1)包含所有完整状态(表2)
然后显示'已完成'(新列)
如果我将状态更改为整数?
同样的程序。谢谢
答案 0 :(得分:7)
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
更新1
您唯一要改变的是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;
答案 1 :(得分:3)
简单但棘手的解决方案:
因为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(还有Andomar的更好解决方案)
答案 2 :(得分:3)
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