db2 在同一个表中使用带条件的计数

pobjuy32  于 2022-11-07  发布在  DB2
关注(0)|答案(1)|浏览(242)
SELECT DISTINCT 
    P.NAME,  L.ID, L.FROM, L.END, L.SALARY, L.NOTE, 
    CASE
        WHEN (MAX(A.END) IS NULL OR MAX(A.END) >= current date ) 
            THEN 'JES' 
            ELSE 'NO' 
    END AS "Have One "

FROM 
    SALARY L 
INNER JOIN 
    CONTACT A ON A.ID = L.ID
INNER JOIN 
    Pep P ON P.ID = L.ID 
WHERE
    L.SALARY = '8000' 
    AND L.END >= CURRENT DATE 
GROUP BY  
    P.NAME, L.ID, L.FROM, L.END, L.SALARY, L.NOTE

我想添加包含结果新列:按人员列出的活动记录的数量。当满足以下条件时,我认为记录是活动的

L.END >= FIRST_DAY(CURRENT DATE) AND L.FROM <= LAST_DAY(CURRENT DATE)

实施例2结果:

|  name  |  ID | FROM      |   END    | SALARY | NOTE | HAVE ONE | ACTIVE
|  KLAR  | 678 |2021-01-01 |2021-09-31|   8000 | GOD  |  YES     |   1
|  KLAR  | 678 |2021-10-01 |2021-12-31|   8000 | GOD  |  YES     |   1
|  TINA  | 676 |2021-01-01 |2021-09-31|   8000 | GOD  |  YES     |   2
|  TINA  | 676 |2021-06-01 |2021-12-31|   8000 | GOD  |  YES     |   2

我该怎么做?

cigdeys3

cigdeys31#

看起来您可以将条件聚合与现有逻辑一起使用,并按如下方式实现新列:

...,
SUM(
  SUM(
    CASE WHEN L.END >= FIRST_DAY(CURRENT DATE)
          AND L.FROM <= LAST_DAY(CURRENT DATE) 
      THEN 1 ELSE 0 END
  )
) OVER (PARTITION BY ID) AS ACTIVE

相关问题