DB2(大型机 DB2)- Select sql - CASE WHEN

DB2 (mainframe DB2) - Select sql - CASE WHEN

我的数据是这样的

SELECT * FROM EMP where EMP_ID=2713729

输出:

EMP_ID      CODE    AMOUNT
2713729     1A      1.00
2713729     2D      1.50

我的要求: 如果有多个CODE,则显示CODE为'MULTI',但如果有一个CODE,则显示那个CODE本身(例如'1A')

我希望我的输出如下(如果数据如上)

代码金额 多 2.50

如果我的数据是这样的:

EMP_ID      CODE    AMOUNT
2713729     1A      1.00

然后我想要如下输出:

CODE        AMOUNT
1A          2.50

我尝试使用以下 SQL,但它抛出错误:

SELECT
    CASE 
        WHEN count(CODE) > 1 THEN 'MULTI'
        WHEN count(CODE) = 1 THEN CODE
    END as CODE,
SUM(AMT) FROM EMP where EMP_ID=2713729 group by EMP_ID

错误:

Error: DB2 SQL Error: SQLCODE=-122, SQLSTATE=42803, SQLERRMC=null, DRIVER=4.19.26
SQLState:  42803
ErrorCode: -122
Error: DB2 SQL Error: SQLCODE=-514, SQLSTATE=26501, SQLERRMC=SQL_CURLH200C1, DRIVER=4.19.26
SQLState:  26501
ErrorCode: -514

如果我努力 'MULTI' 和代码,那么我得到了结果。

SELECT
    CASE 
        WHEN count(CODE) > 1 THEN 'MULTI'
        WHEN count(CODE) = 1 THEN 'SINGLE'
    END as CODE,
SUM(AMT) FROM EMB where EMP_ID=2713729 group by EMP_ID

可是我不想硬了'SINGLE'

你试过了吗:

SELECT
    E1.EMP_ID,
    CASE WHEN ECNT.CODECNT > 1 THEN 'MULTI' ELSE CODE END as CODE,
    SUM(E1.AMOUNT) 
FROM EMP E1
     inner join
     (select EMP_ID, count(*) as CODECNT
      FROM EMP E2
      GROUP BY EMP_ID
     ) as ECNT
     on E1.EMP_ID=ECNT.EMP_ID
where E1.EMP_ID=2713729 
group by 
    E1.EMP_ID,
    CASE WHEN ECNT.CODECNT > 1 THEN 'MULTI' ELSE CODE END

注意:如果同一个 EMP_ID 有其他行具有相同的代码,它将标记它们 'MULTI'。如果这是不可取的,请将 count(*) 更改为 count(DISTINCT CODE)。

或者这个:

SELECT 
      EMP_ID
    , CODE
    , SUM(AMOUNT)
FROM (
    SELECT
        E1.EMP_ID,
        CASE WHEN EXISTS (SELECT * FROM EMP E2 WHERE E2.EMP_ID=E1.EMP_ID and E2.CODE<>E1.CODE) THEN 'MULTI' ELSE CODE END as CODE,
        E1.AMOUNT
    FROM EMP E1
    ) Step1
where Step1.EMP_ID=2713729 
GROUP BY 
      EMP_ID
    , CODE 

试试这个。如果您取消注释掉的块,您可以运行按原样检查此语句。

/*
WITH EMP (EMP_ID, CODE, AMOUNT) AS
(
          SELECT 2713729, '1A', 1.00 FROM SYSIBM.SYSDUMMY1
UNION ALL SELECT 2713729, '2D', 1.50 FROM SYSIBM.SYSDUMMY1
)
*/
SELECT
  CASE 
    WHEN count (CODE) > 1 THEN 'MULTI'
    WHEN count (CODE) = 1 THEN MAX (CODE)
  END as CODE
, SUM (AMOUNT) AS AMOUNT
FROM EMP 
where EMP_ID = 2713729
group by EMP_ID