sql列排列

af7jpaap  于 2021-06-24  发布在  Hive
关注(0)|答案(3)|浏览(337)

我有一个如下所示的采购表:

store_id.   industry_code    amt_age_18_24    amt_age_25-34    amt_men    amt_women
       1             1000              100               20         80           40
       2             2000              100              100        130           70

我要做的是找出每家商店按年龄和性别排列的每一种购物方式。就像这样,每一行都是唯一的:

store_id.   industry_code    amt_age_18_24    amt_age_25-34    amt_men    amt_women
       1             1000              100             NULL         80          NULL
       1             1000              100             NULL        NULL           40
       1             1000              NULL            20           80          NULL
       1             1000              NULL            20          NULL           80
       2             2000              100             NULL        130          NULL
       2             2000              100             NULL        NULL           70
       2             2000              NULL            100         130          NULL
       2             2000              NULL            100         NULL           70

最好的办法是什么?自动加入?

1szpjjfi

1szpjjfi1#

这看起来像 union all :

select store_id, instrustry_code, amt_age_18_24, null as amt_age_25_34, amt_men, null as amt_women
from t
union all
select store_id, instrustry_code, amt_age_18_24, null as amt_age_25_34, null as amt_men, amt_women
from t
union all
. . .
dy1byipe

dy1byipe2#

您可以根据需要对每个排列使用并集:

select store_id, instrustry_code, amt_age_18_24, null as amt_age_25_34, amt_men, null as amt_women
from t
union all
select store_id, instrustry_code, amt_age_18_24, null as amt_age_25_34, null as amt_men, amt_women
from t

你想做多少列就做多少列

yrwegjxp

yrwegjxp3#

下面是一个使用 cross join 对于包含“列掩码”的派生表:

select 
    t.store_id, 
    t.industry_code, 
    t.amt_age_18_24 * x.amt_age_18_24 as amt_age_18_24,
    t.amt_age_25_34 * x.amt_age_25_34 as amt_age_25_34,
    t.amnt_men      * x.amnt_men      as amnt_men,
    t.amt_women     * x.amt_women     as amt_women
from mytable t
cross join (
    select 1 as amt_age_18_24, null as amt_age_25_34, 1 as amnt_men, null as amt_women
    union all select 1, null, null, 1
    union all select null, 1, 1, null
    union all select null, 1, null, 1
) x

好处是,这不需要多次扫描表,而不是 union all 接近。

相关问题