8

这是我的两个表的示例。

在此处输入图像描述

问题: 如何使用左连接创建 SQL 查询?

这是场景

正如我之前所说,我有两个表(TABLE1 和 TABLE2),我尝试使用左连接,以便可以将两个 UserID 组合在一个表中

所以这是代码

select * from table1 a left join table2 on a.userid = b.userid

所以现在合并了两个表。

我需要做的是:
如果状态全部完成,则“完成”,
然后如果状态包含完整和不完整,则“不完整”,
否则“无状态”

它应该是这样的。

在此处输入图像描述

注意
由于UserID = 1 (table1) 包含完整和不完整状态 (table2)
然后它显示“不完整” (新列)

因为UserID = 4 (table1) 包含所有完整状态 (表 2)
然后它显示“完成” (新柱子)

----------------------------------

如果我将状态更改为整数会怎样?

在此处输入图像描述

相同的程序。谢谢

4

3 回答 3

12
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;
于 2013-02-06T15:29:55.623 回答
4

简单但棘手的解决方案:

因为 INCOMPLETE 比 COMPLETE 大(对于一个 db),你可以简单地做

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 更好的解决方案)

于 2013-02-06T15:26:16.500 回答
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
于 2013-02-06T15:28:47.290 回答