如何在sqlite中使用交叉表/数据透视进行计算?

时间:2012-01-10 15:44:54

标签: sql sqlite pivot

要在sqlite中执行交叉表/数据透视,可以使用所述的case语句,例如here。但是,无法对此类“生成”列进行计算,即将“Puma”列的内容除以“Fiesta”列。

我的解决方法是创建一个辅助view,其中包含'Puma'和'Fiesta'列以及joinview到主'交叉表'输出,并将列分开加入的辅助表。

CREATE VIEW aux_table AS SELECT
    shop_id,
    sum(CASE WHEN product = 'Fiesta' THEN units END) as Fiesta,
    sum(CASE WHEN product = 'Focus' THEN units END) as Focus`
FROM sales
GROUP BY shop_id;

SELECT 
    shop_id,
    sum(CASE WHEN product = 'Fiesta' THEN units END) as Fiesta,
    sum(CASE WHEN product = 'Focus' THEN units END) as Focus,
    sum(CASE WHEN product = 'Puma' THEN units END) as Puma,
    at.Fiesta/at.Focus 'ratio between Fiesta and Focus'
FROM sales
JOIN aux_table at ON
     sales.shop_id = at.shop_id
GROUP BY shop_id;

但我想知道是否有一种更简单的方法可以做到这一点。

1 个答案:

答案 0 :(得分:2)

您可以随时再次执行这些操作,如下所示:

SELECT 
    shop_id,
    sum(CASE WHEN product = 'Fiesta' THEN units END) as Fiesta,
    sum(CASE WHEN product = 'Focus' THEN units END) as Focus,
    sum(CASE WHEN product = 'Puma' THEN units END) as Puma,
    sum(CASE WHEN product = 'Fiesta' THEN units END) / sum(CASE WHEN product = 'Focus' THEN units END) as Ratio
FROM sales
GROUP BY shop_id

或者,更快,您可以将其包装在子查询中,如下所示:

select
    shop_id,
    Fiesta,
    Focus,
    Puma,
    Fiesta/Focus as Ratio
from
    (
    SELECT 
        shop_id,
        sum(CASE WHEN product = 'Fiesta' THEN units END) as Fiesta,
        sum(CASE WHEN product = 'Focus' THEN units END) as Focus,
        sum(CASE WHEN product = 'Puma' THEN units END) as Puma
    FROM sales
    GROUP BY shop_id
    ) x