SQL - 如果条件存在,则对具有计数的某些记录进行分组

时间:2013-12-13 18:10:23

标签: sql oracle

我正在尝试编写一个查询,如果一个字段具有特定值,则会对某些记录进行分组,并返回分组记录的计数,而不是其中一个字段。到目前为止我已经有了这个:

SELECT DISTINCT A.PDP_DESC,
       CASE WHEN A.PLI LIKE '%DF' THEN (
                 SELECT COUNT(A.ASSET_ID)
                 FROM QL_ASSETS A
                 WHERE A.WARNING_TYPE = 'ABC'
                 AND A.CHANGE_TYPE = 'DEF'
                 GROUP BY A.ASSET_ID) || ' feed users' 
            ELSE A.USER_ID 
       END AS USER_ID,
FROM QL_ASSETS A 
WHERE A.WARNING_TYPE = 'ABC'
AND A.CHANGE_TYPE = 'DEF'

如果A.PLI以'DF'结尾,我希望将所有这些记录组合在一起,并在A.USER_ID字段中显示'XX feed'用户。现在我收到了一个不一致的数据类型错误,但我很确定查询还有其他问题。有什么想法吗?

修改

所有字段均为VARCHAR2

示例数据:

PDP_DESC     PLI        USER_ID   ASSET_ID    WARNING_TYPE  CHANGE_TYPE

DT1          ABCDE      joe       11111       ABC           DEF
Feed1        XYZ-DF     jack      11112       ABC           DEF
Feed1        XYZ-DF     will      11113       ABC           DEF
Feed2        ABC-DF     john      11114       ABC           DEF
DT1          ABCDE      jill      11115       ABC           DEF

这里想要的结果是:

PDP_DESC     USER_ID

DT1          joe
Feed1        2 feed users
Feed2        1 feed users
DT1          jill

2 个答案:

答案 0 :(得分:2)

SQL Fiddle

Oracle 11g R2架构设置

CREATE TABLE test ( PDP_DESC,      PLI,        USER_ID,   ASSET_ID,    WARNING_TYPE,  CHANGE_TYPE ) AS
          SELECT 'DT1',          'ABCDE',      'joe',       '11111',       'ABC',           'DEF' FROM DUAL
UNION ALL SELECT 'Feed1',        'XYZ-DF',     'jack',      '11112',       'ABC',           'DEF' FROM DUAL
UNION ALL SELECT 'Feed1',        'XYZ-DF',     'will',      '11113',       'ABC',           'DEF' FROM DUAL
UNION ALL SELECT 'Feed2',        'ABC-DF',     'john',      '11114',       'ABC',           'DEF' FROM DUAL
UNION ALL SELECT 'DT1',          'ABCDE',      'jill',      '11115',       'ABC',           'DEF' FROM DUAL;

查询1

SELECT PDP_DESC,
       COUNT(1) || ' feed users' AS USER_ID
FROM   test
WHERE  SUBSTR( PLI, -2 ) = 'DF' 
AND    WARNING_TYPE = 'ABC'
AND    CHANGE_TYPE = 'DEF'
GROUP BY PDP_DESC
UNION ALL
SELECT PDP_DESC,
       USER_ID
FROM   test
WHERE  SUBSTR( PLI, -2 ) <> 'DF'
AND    WARNING_TYPE = 'ABC'
AND    CHANGE_TYPE = 'DEF'

<强> Results

| PDP_DESC |      USER_ID |
|----------|--------------|
|    Feed1 | 2 feed users |
|    Feed2 | 1 feed users |
|      DT1 |          joe |
|      DT1 |         jill |

答案 1 :(得分:1)

Upvoted MTD因为我更喜欢他的解决方案,但这是我提出的:

WITH cte AS (
  SELECT 
    PDP_DESC,
    CASE WHEN PLI LIKE '%DF' THEN 'feed users' ELSE USER_ID END AS USER_ID
  FROM QL_ASSETS
  WHERE WARNING_TYPE = 'ABC'
  AND CHANGE_TYPE = 'DEF'
)
SELECT
  PDP_DESC,
  CASE 
    WHEN USER_ID = 'feed users' THEN COUNT(USER_ID) || ' feed users'
    ELSE USER_ID 
  END AS USER_ID
FROM cte
GROUP BY PDP_DESC, USER_ID;