db2 如何在SQL中使一列的值固定并根据该列显示结果?

s5a0g9ez  于 2023-11-18  发布在  DB2
关注(0)|答案(1)|浏览(299)
SELECT 
    CASE 
        WHEN LEFT(DATA.LICLVS, 5) = '99999' 
            THEN 'Priority 2' 
            ELSE  'Priority 1' 
    END AS Type, 
    COUNT (distinct LIVUID) as userh1 
FROM
    DATA 
WHERE 
    UPPER(LIVUID) <> 'ADMIN' 
    AND TRIM(LIVUID) IS NOT NULL 
    AND UPPER(LIVUID) <> 'ICMADMIN' 
    AND UPPER(LIVUID) <> 'CONTINGENC' 
    AND UPPER(LIVUID) <> 'INDEXUPDAT'   
    AND LOCALDATA.LICRTD = '20211122' 
    AND LIVUID <> ''
    AND CASE WHEN VARCHAR_FORMAT(TIMESTAMP(CREATETS) + CURRENT TIMEZONE, 'HH24') = '09' 
    AND (CAST(VARCHAR_FORMAT(TIMESTAMP(CREATETS) + CURRENT TIMEZONE, 'MI') AS DECIMAL(8,2))  <= 29) THEN 1 END = 1
GROUP BY 
    CASE
        WHEN LEFT(DATA.LICLVS, 5) = '99999' 
            THEN 'Priority 2' 
            ELSE 'Priority 1' 
    END,
    CASE 
        WHEN VARCHAR_FORMAT(TIMESTAMP(CREATETS) + CURRENT TIMEZONE, 'HH24') = '09' 
             AND (CAST(VARCHAR_FORMAT(TIMESTAMP(CREATETS) + CURRENT TIMEZONE, 'MI') AS DECIMAL(8, 2)) >= 0 
             AND CAST(VARCHAR_FORMAT(TIMESTAMP(CREATETS) + CURRENT TIMEZONE, 'MI') AS DECIMAL(8,2))  <= 29) 
           THEN 1 
    END

我得到的结果如附件所示,我想使类型列固定为优先级1和优先级2,并根据它显示userh1。
即使优先级1的用户h1不在那里,它也应该显示0。
现在,它基于优先级1和优先级2进行分组,如果优先级1中没有userh1,则不会显示该行。
非常感谢您的帮助。谢谢
When 'HH24'=01
When 'HH24'=09

06odsfpq

06odsfpq1#

如果有一组值需要始终出现在输出中,则可以将它们指定为子查询,然后执行左连接。

SELECT v.[type], COALESCE(SUM(q.[userh1]), 0) as [userh1]
FROM 
    (VALUES ('Priority 1'),('Priority 2')) v ([type])
    LEFT JOIN (

        /* your query here */

        ) q ON q.[type] = v.[Type]
GROUP BY v.[Type]
ORDER BY v.[Type];

相关问题