Hive case when+group by组合使用的问题

765 阅读1分钟

0 源表

        select
            11 as order_id,
            '2022-01-02 ' as order_day,
            1 as qty
        union all
        select
            12 as order_id,
            '2022-02-02' as order_day,
            2 as qty
        union all
        select
            13 as order_id,
            '2022-03-02' as order_day,
            3 as qty
        union all
        select
            14 as order_id,
            '2022-04-02' as order_day,
            4 as qty

1 报错,因为没有通过聚合或别名或常量生成新的字段.【5正确】

-- CalciteContextException: Sql 1: From line 4, column 14 to line 4, column 21: Expression 'order_id' is not being grouped
select
    order_day,
    case
        when order_id = 11 then 111
    end as c1,
    case
        when order_id = 12 then 222
    end as c2
from
    (
        source
    ) t1
group by
    order_day

2 正确

select
    order_day,
    order_id,
    case
        when order_id = 11 then 1
    end as c1,
    case
        when order_id = 12 then 1
    end as c2
from
    (
        source
    ) t1
group by
    order_day,
    order_id;

2.png

3 正确

select
    order_day,
    case
        when order_id = 11 then 111
    end as c1,
    case
        when order_id = 12 then 222
    end as c2
from
    (
        source
    ) t1
group by
    order_day,
    order_id;

3.png

4 正确

select
    order_day,
    order_day as order_day2,
    case
        when order_id = 11 then 111
    end as c1,
    case
        when order_id = 12 then 222
    end as c2
from
    (
       source
    ) t1
group by
    order_day,
    order_id;

4.png

5 正确

select
    order_day,
    sum(
        case
            when order_id = 11 then 111
        end
    ) as c1,
    sum(
        case
            when order_id = 12 then 222
        end
    ) as c2
from
    (
        source
    ) t1
group by
    order_day

5.png