0

我经常有一些查询,我想在其中按 case 子句进行分组,例如:

SELECT
    CASE WHEN FIELD IS NULL                     |
    AND (SOMETHING > 100 OR SOMETHINGELSE < 50) |
    AND THATDATE >= add_months(sysdate, -4)     | -> Case
        THEN 0 ELSE 1                           |                                                               
    END AS dim_1,                               |                                                               
    dim_2,
    sum(SOMEFIELD_TOTAL) as measure_1
FROM MY_TABLE
GROUP BY
    CASE WHEN FIELD IS NULL                     | 
    AND (SOMETHING > 100 OR SOMETHINGELSE < 50) | 
    AND THATDATE >= add_months(sysdate, -4)     | -> Same case
        THEN 0 ELSE 1                           |                                                                
    END,                                        |                                                                
    dim_2

有没有办法可以将我为整个案例定义的别名用于group by, 像, group by dim_1

找到了这个解释,我仍然想知道是否有出路。

4

2 回答 2

3

我认为您过度关注重复表达。Oracle 和任何其他 DBMS 都会将该表达式识别为重复项并仅计算一次。如果您只是不想重复它(请注意,这只是剪切和粘贴的琐事),您可以使用派生表或公用表表达式。

SELECT 
    dim_1, dim_2, sum(SOMEFIELD_TOTAL) as measure_1
FROM (
    SELECT
        CASE WHEN FIELD IS NULL                     |
        AND (SOMETHING > 100 OR SOMETHINGELSE < 50) |
        AND THATDATE >= add_months(sysdate, -4)     | -> Case
            THEN 0 ELSE 1                           |                                                               
        END AS dim_1,                               |                                                               
        dim_2,
        SOMEFIELD_TOTAL
    FROM MY_TABLE
) AS SQ
GROUP BY
    dim_1, dim_2

它看起来并没有更好,不是吗?

于 2012-10-28T19:24:43.610 回答
1

你可以使用subquery factoring也知道named subquerycommon table expression (CTE)(感谢@a_horse_with_no_name)

WITH t as 
(
SELECT
    CASE WHEN FIELD IS NULL                     
    AND (SOMETHING > 100 OR SOMETHINGELSE < 50) 
    AND THATDATE >= add_months(sysdate, -4)     
        THEN 0 ELSE 1 END AS dim_1,         
    dim_2,
    SOMEFIELD_TOTAL as measure_1
FROM MY_TABLE
)
SELECT dim_1, dim_2, sum(SOMEFIELD_TOTAL)
FROM t
GROUP BY dim_1, dim_2

这种方法的优点是您可以拥有许多子查询,而不必像在常规子查询中那样加入它们(内部选择)

于 2012-10-29T05:43:05.930 回答