sql—连接两个查询,并且在没有匹配项时设置默认值

sgtfey8w  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(303)

是否可以合并以下两个查询,并具有默认值 offline 为了 status 当它没有匹配的条目时?

示例:

SELECT
    Objects,
    COUNT(*) AS Objects_count
FROM
    table1
GROUP BY
    Objects
---------------------------------
Objects         |   Objects_count
---------------------------------
Unitied_states  |   2           
Germany         |   2           
Turkey          |   1           
Kuwait          |   2

第二个查询:

注:当状态不等于1时,表2中没有该项。所以在表2中我们只有在线的条目。

SELECT
    Objects, 
    CASE 
        WHEN status = 1 THEN 'ONLINE'
    END AS Status
FROM
    table2
WHERE
    status = 1
GROUP BY
    Objects
--------------------------
Objects         |   Status
--------------------------
Unitied_states  |   Online          
Turkey          |   Online

我希望最终的输出是

-------------------------------------------
Objects         |   Objects_count  | Status
-------------------------------------------
Unitied_states  |   2              | Online
Germany         |   2              | Offline
Turkey          |   1              | Online
Kuwait          |   2              | Offline
50pmv0ei

50pmv0ei1#

是的,这是可能的,通过做一个 FULL OUTER JOIN .
我也认为你想 JOINObjects 列:

SELECT
    COALESCE( t1.Objects, t2.Objects ) AS Objects,
    COALESCE( t1.Objects_Count, 0 ) AS Objects_Count,
--  t2.Status,
    CASE t2.status WHEN 1 THEN 'Online' ELSE 'Offline' END AS status
FROM
    (
        SELECT
            Objects,
            COUNT(*) AS Objects_count
        FROM
            table1
        GROUP BY
            Objects

    ) AS t1

    FULL OUTER JOIN
    (
        SELECT
            Objects, 
            status
        FROM
            table2

    ) AS t2 ON t1.Objects = t2.Objects
dldeef67

dldeef672#

使用以下命令尝试 left join 上的表1和表2 Objects .

select 
    t1.Objects, 
    coalesce(COUNT (t1.*), 0) as  Objects_count,
    case 
        when t2.status = 1 then 'Online'
        else 'Offline'
    end as Status 
from table1 t1
left join table2 t2
on t1.Objects = t2.Objects
GROUP BY 
    Objects,  
    case 
        when t2.status = 1 then 'Online'
        else 'Offline'
    end
owfi6suc

owfi6suc3#

我将使用相关子查询:

SELECT t1.Objects, COUNT(*) AS Objects_count,
       (CASE WHEN EXISTS (SELECT 1
                          FROM table2 t2
                          WHERE t2.Objects = t1.Objects AND t2.status = 1
                         )
             THEN 'Online' ELSE 'Offline'
        END) as status
FROM table1 t1
GROUP BY t1.Objects

这将返回 table1 以及状态。
或者,如果 table2 没有重复行,可以使用简单的 LEFT JOIN 和聚合:

SELECT t1.Objects, COUNT(*) AS Objects_count,
       (CASE WHEN COUNT(t2.Objects) > 0 THEN 'Online' ELSE 'Offline' END) as status
FROM table1 t1 LEFT JOIN
     table2 t2
     ON t2.Objects = t1.Objects AND t2.status = 1
GROUP BY t1.Objects;

相关问题