SQL Sum多个Case条件

时间:2018-02-02 19:45:18

标签: sql db2

我的数据库位于IBM上,是DB2。我有两个问题希望加入,但是当我这样做时,他们并不是很有效。该报告是租赁利用率

  1. 第一个查询从 CGIHIST (历史)表和 CGIBASE (设备配置文件)表中提取机器信息。

  2. 第二个查询会提取 Rental 信息。在此查询中,我在比较两个日期时使用多个条件执行了Case语句。

  3. 我使用 DBXTRA 作为我的报告构建工具,当我链接它们时,我希望能够对Case语句求和。不幸的是,它不会让我。

    我希望通过股票编号链接第一个查询,然后将第二个查询case语句中的所有值相加。我尝试在sum前放置case,但这不起作用。

    有什么想法吗?

    第一次查询:

    SELECT CBORD AS "STK", CBMSN AS "SN"
    FROM PFWF0022.CGIBASE
    LEFT JOIN PFWF0022.CGIHIST
    ON CBORD = CHORD
    WHERE CBGLIA IN('13100','13150') AND CBCAT <> '' AND CBSTA NOT IN('I','T','O','D','S','P')
    GROUP BY CBORD, CBMSN 
    ORDER BY cbord
    limit 100
    

    第二次质疑:

    SELECT RDBR AS "BR", RDCONT AS "CONT", RDSTK AS "STK", RDRDUR AS "DUR", RDPRC AS "PRC",
    CASE
    WHEN RDDATI = 0 AND DAYS(substr(RDDATO, 5, 2) || '/' || substr(RDDATO, 7, 2) || '/' || substr(RDDATO, 1, 4)) >= DAYS(CURRENT DATE) THEN '0'
    WHEN RDDATI = 0 and DAYS(substr(RDDATO, 5, 2) || '/' || substr(RDDATO, 7, 2) || '/' || substr(RDDATO, 1, 4)) < DAYS(CURRENT DATE - 90 DAYS) THEN '90'
    WHEN RDDATI = '0' AND DAYS(substr(RDDATO, 5, 2) || '/' || substr(RDDATO, 7, 2) || '/' || substr(RDDATO, 1, 4)) >= DAYS(CURRENT DATE - 90 DAYS) THEN DAYS(CURRENT DATE) - DAYS(substr(RDDATO, 5, 2) || '/' || substr(RDDATO, 7, 2) || '/' || substr(RDDATO, 1, 4))
    WHEN DAYS(substr(RDDATO, 5, 2) || '/' || substr(RDDATO, 7, 2) || '/' || substr(RDDATO, 1, 4)) < DAYS(CURRENT DATE - 90 DAYS) AND DAYS(substr(RDDATI, 5, 2) || '/' || substr(RDDATI, 7, 2) || '/' || substr(RDDATI, 1, 4)) >= DAYS(CURRENT DATE - 90 DAYS) THEN DAYS(substr(RDDATI, 5, 2) || '/' || substr(RDDATI, 7, 2) || '/' || substr(RDDATI, 1, 4)) - DAYS(CURRENT DATE - 90 DAYS)
    WHEN DATE(substr(RDDATO, 5, 2) || '/' || substr(RDDATO, 7, 2) || '/' || substr(RDDATO, 1, 4)) < DATE(DAYS(CURRENT DATE - 90 DAYS)) AND DATE(substr(RDDATI, 5, 2) || '/' || substr(RDDATI, 7, 2) || '/' || substr(RDDATI, 1, 4)) < DATE(DAYS(CURRENT DATE - 90 DAYS)) THEN '0'
    WHEN DAYS(substr(RDDATO, 5, 2) || '/' || substr(RDDATO, 7, 2) || '/' || substr(RDDATO, 1, 4)) >= DAYS(CURRENT DATE - 90 DAYS) AND DAYS(substr(RDDATI, 5, 2) || '/' || substr(RDDATI, 7, 2) || '/' || substr(RDDATI, 1, 4)) >= DAYS(CURRENT DATE - 90 DAYS) THEN DAYS(substr(RDDATI, 5, 2) || '/' || substr(RDDATI, 7, 2) || '/' || substr(RDDATI, 1, 4)) - DAYS(substr(RDDATO, 5, 2) || '/' || substr(RDDATO, 7, 2) || '/' || substr(RDDATO, 1, 4))
    ELSE 555 END AS "90DAYCNT"
    FROM PFWF0022.RMDETL
    WHERE RDSTK <> '' 
    GROUP BY RDBR, RDCONT, RDSTK, RDRDUR, RDPRC, RDDATI, RDDATO
    ORDER BY RDCONT DESC
    LIMIT 100
    

0 个答案:

没有答案