2012-01-10 45 views
0

要在sqlite中執行交叉表/數據透視表,可以使用case聲明,如here。但是,無法對這些'生成'列進行計算,即將'Puma'列的內容除以'Fiesta'列。如何在sqlite中通過大小寫進行crosstab/pivot計算?

我的解決辦法一直是創建包含「彪馬」和「嘉年華」列和joinview到主「交叉」的輸出的輔助view和從接合輔助表劃分的列。

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; 

但我不知道是否有一個更簡單的方法來做到這一點。

回答

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 
+0

謝謝,我想我只是試過:「(CASE WHEN ...)/(CASE WHEN ...)'而不是'avg((CASE WHEN ...)/ avg(CASE WHEN ...)',就像我的情況一樣不需要「平均」,「和」等。 – sseelenluft 2012-01-10 16:54:44

相關問題