微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

列的SQL置换

如何解决列的SQL置换

我有一个如下的购买表:

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

执行此操作的最佳方法是什么?自我加入?

解决方法

这看起来像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,null as amt_men,amt_women
from t
union all
. . . 
,

这是将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,1 as amnt_men,null as amt_women
    union all select 1,null,1
    union all select null,1,null
    union all select null,1
) x

union all方法相反,这样做的好处是不需要多次扫描表。

,

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

select store_id,amt_women
from t

并根据需要执行任意多的列

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。