SQL:加入PIVOT

时间:2017-05-04 18:05:27

标签: sql pivot crosstab

新手问题:

我有下表

In [154]: N,D,K,T = 3,4,5,6
     ...: a = np.random.randint(0,5,(D,K,T))
     ...: 
     ...: p = pd.DataFrame(np.random.randint(0,T,(N,D)).astype(float))
     ...: p.iloc[2,3] = np.nan
     ...: p.iloc[1,2] = np.nan
     ...: 

In [155]: result = np.fromfunction(vgenerate_entry, shape=(len(p), K), dtype=int)

In [156]: a_indexed_vals = fancy_indexing_avoid_NaNs(p, a)

In [157]: out = a_indexed_vals.prod(2).T

In [158]: np.allclose(out, result)
Out[158]: True

我想订购它,以便每个时期都有一列,

Period Customer Balance
40     1        10
40     2        15
39     1        9
38     1        10
38     2        20

这可能吗?

1 个答案:

答案 0 :(得分:0)

您可以使用以下情况使用聚合转发数据:

select customer,
    sum(case when period = 38 then balance else 0 end) as balance_period_38,
    sum(case when period = 39 then balance else 0 end) as balance_period_39,
    sum(case when period = 40 then balance else 0 end) as balance_period_40
from your_table
group by customer;