如何在Group By中使用Case Statement列

时间:2013-11-27 14:35:35

标签: sql db2

正如问题所述,我正在尝试在列结果中制定一个包含case语句的查询,然后我想在查询的group by语句中包含该列。举一个具体的例子,这里几乎没有我的查询:

SELECT SOME_TABLE_ALIAS.COLUMN1, OTHER_TABLE_ALIAS.COLUMN2,
CASE
    WHEN SOME_TABLE_ALIAS.COLUMN3 IS NOT NULL THEN 'A'
    ELSE 'B'
END AS CASE_COLUMN
FROM SOME_TABLE SOME_TABLE_ALIAS
... (other table joins and where clauses)
GROUP BY SOME_TABLE_ALIAS.COLUMN1, OTHER_TABLE_ALIAS.COLUMN2, CASE_COLUMN

在来到这里之前,我查看了一些网站,包括this one,以尝试解决我的问题。我已经尝试在链接网页中显示CASE关键字之后添加另一个别名,但没有运气。我继续收到的错误消息如下:

[Error] Script lines: 127-151 ----------------------
 CASE_COLUMN IS NOT VALID IN THE CONTEXT WHERE IT IS USED. SQLCODE=-206, SQLSTATE=42703, DRIVER=3.53.71 

是否有其他人遇到我正面临的问题,并且能够对GROUP BY声明的结果使用CASE?任何帮助,将不胜感激。哦,DB2版本是z / OS实例,版本10(DSN10015)

2 个答案:

答案 0 :(得分:20)

别名不能在GROUP BY中使用,因为当GROUP BY发生时,别名尚未定义:

Here's the order:
1.FROM
2.WHERE
3.GROUP BY
4.HAVING
5.SELECT
6.ORDER BY

你可以通过以下方式解决这个问题:

SELECT column1,column2,case_column
FROM (
SELECT SOME_TABLE_ALIAS.COLUMN1, OTHER_TABLE_ALIAS.COLUMN2,
CASE
    WHEN SOME_TABLE_ALIAS.COLUMN3 IS NOT NULL THEN 'A'
    ELSE 'B'
END AS CASE_COLUMN
FROM SOME_TABLE SOME_TABLE_ALIAS
... (other table joins and where clauses)
) a
GROUP BY COLUMN1, COLUMN2, CASE_COLUMN

或者只使用您在GROUP BY中的SELECT中使用的案例

答案 1 :(得分:7)

您可以按原样使用案例,如下所示:

SELECT SOME_TABLE_ALIAS.COLUMN1, OTHER_TABLE_ALIAS.COLUMN2,
CASE
    WHEN SOME_TABLE_ALIAS.COLUMN3 IS NOT NULL THEN 'A'
    ELSE 'B'
END AS CASE_COLUMN
FROM SOME_TABLE SOME_TABLE_ALIAS
... (other table joins and where clauses)
GROUP BY SOME_TABLE_ALIAS.COLUMN1, OTHER_TABLE_ALIAS.COLUMN2, 
CASE
    WHEN SOME_TABLE_ALIAS.COLUMN3 IS NOT NULL THEN 'A'
    ELSE 'B'
END

或使用像这样的子查询:

select COLUMN1, COLUMN2, CASE_COLUMN
from (
    SELECT SOME_TABLE_ALIAS.COLUMN1, OTHER_TABLE_ALIAS.COLUMN2,
    CASE
        WHEN SOME_TABLE_ALIAS.COLUMN3 IS NOT NULL THEN 'A'
        ELSE 'B'
    END AS CASE_COLUMN
    FROM SOME_TABLE SOME_TABLE_ALIAS
    ... (other table joins and where clauses)
) a
GROUP BY COLUMN1, COLUMN2, CASE_COLUMN