选择查询与条件检查的记录组

时间:2018-06-22 19:13:07

标签: sql impala

SELECT DISTINCT
    t2.cmdb_id,
    t1.src_sys_id,
    t3.appl_nm,
    t1.st_mgmnt_cd Status,
    CASE 
       WHEN t1.st_mgmnt_cd != "PURGE" 
          THEN 'In-Progress' 
       ELSE 'In-Compliance' 
    END as Status,
    t1.podium_delivery_date
FROM
    table1 t1 
JOIN 
    table2 t2 
JOIN 
    table3 t3 
WHERE
    t1.src_sys_id = t2.ingstn_nm 
    AND t2.cmdb_id = t3.cmdb_id

以上查询返回许多行,其中重复了状态列。这是因为在原始表上,除清除列st_mgmnt_cd以外,我还有许多其他状态。但是我需要检查cmdb_id下的所有记录。因此,对于cmdb_id,根据检查,我只需要在结果和状态中显示一行即可。

如何重写查询以对cmdb_id的记录进行检查?

cmdb_id schema_name        appl_nm  status  assessment_date
88      PAD                PADCOD   HOT     20180601
88      PAD                PADCOD   WARM    20180601
218     EED                EEDCOD   HOT     20180617
218     EED                EEDCOD   WARM    20180618
218     EED                EEDCOD   COLD    20180620
3106    ABC                ABCOD    HOT     20180601
3106    ABC                ABCOD    WARM    20180604
3106    ABC                ABCOD    EXPIRED 20180620
3106    ABC                ABCOD    PURGE   20180622

预期结果  ==================

 88   PAD   PADCOD  In-Progress     20180601
 218  EED   EEDCOD  In-Progress     20180620
 3106 ABC   ABCOD   In-Compliance   20180620

2 个答案:

答案 0 :(得分:0)

将查询中的内容封装为SELECT,以更改内部查询中的max(st_mgmntcd)。

即 SELECT COL1,数据来自( 通过COL1)选择COL1,MAX(REPETINGCOL)作为数据组x

答案 1 :(得分:0)

为了将来:使用可现场测试的东西

DB-Fiddle

我省略了对其他表的联接,并添加了字段id来联接表temp,但是您应该明白这个概念。 :)

假设您想要每个cmdb_id的最新条目。为此,我使用了新字段id,但是您可以按照相同的方式使用字段podium_delivery_date

# assume joins have been made
SELECT
    t1.cmdb_id,
    t1.appl_nm,
    t1.st_mgmnt_cd Status,
    CASE 
       WHEN t1.st_mgmnt_cd != "PURGE" 
          THEN 'In-Progress' 
       ELSE 'In-Compliance' 
    END as Status,
    t1.podium_delivery_date
FROM
    table1 t1
    JOIN 
      (SELECT
          tx.cmdb_id,
          MAX(tx.id) as highest_id_of_group
      FROM
          table1 tx
      GROUP BY
          tx.cmdb_id) as temp
    ON temp.highest_id_of_group = t1.id

请记住要放置好索引!