DB2(大型机DB2)-选择sql - CASE WHEN

yv5phkfx  于 2022-11-07  发布在  DB2
关注(0)|答案(2)|浏览(272)

我的数据是这样的

SELECT * FROM EMP where EMP_ID=2713729

输出:

EMP_ID      CODE    AMOUNT
2713729     1A      1.00
2713729     2D      1.50

我的要求:如果有多个代码,则将代码显示为“多个”,但如果有一个代码,则显示该代码本身(例如“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

如果我硬'多'和代码,那么我得到的结果。

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

"但我不想让“单身”变硬“

vlju58qv

vlju58qv1#

您是否尝试过:

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中的其它行具有相同的CODE,则系统会将这些行标记为'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
jxct1oxe

jxct1oxe2#

如果你取消注解掉的块,你可以运行这个语句来检查。

/*
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

相关问题