2016-04-23 53 views
2

建立這個查詢我對形式的事務日誌表:MySQL的:無子選擇

| id | date  | type | symbol | volume | unit_price | user_id | 
| 1 | 2016-01-01 | BUY | AAPL | 100 | 100.00  | a  | 
| 2 | 2016-01-02 | SELL | AAPL | 50  | 110  | a  | 

我試圖建立一個視圖,顯示基於這些交易的當前餘額。一些形式:

| user_id | symbol | total_volume | value | 

到目前爲止,我有:

SELECT 
    t.user_id, 
    t.symbol, 
    sum(t.volume * t.multiplier) as total_volume, 
    sum(t.volume * t.unit_price * t.multiplier) as value 
FROM (
    SELECT 
     *, 
     CASE type 
      WHEN 'SELL' THEN -1 
      WHEN 'BUY' THEN 1 
     END as multiplier 
    FROM transaction 
) t 
GROUP BY t.user_id, t.symbol; 

這讓我我需要什麼,但我不能創建此作爲,因爲子選擇的景色。有沒有另外一種方法可以做到這一點,使我能夠創建它作爲一個視圖?

+0

什麼錯誤,你當你試圖做這個查詢進入一個視圖? – Mureinik

+0

@Mureinik只是一個通用的「創建視圖時出錯」,但我知道MySql不允許在視圖中進行子查詢,所以最有可能的是 – Edd

+1

只需將內聯視圖查詢替換爲對事務表的引用即可。 然後用CASE表達式替換對't.multiplier'的引用。無論是否需要,它應該會有更好的表現。 – spencer7593

回答

3

只需使用條件在sum

SELECT t.user_id, t.symbol, 
     sum(case when t.type = 'SELL' then - volume 
       when t.type = 'BUY' then volume 
      end) 
     ) as total_volume, 
     sum(t.volume * t.unit_price * 
      (case when t.type = 'SELL' then -1 
       when t.type = 'BUY' then 1 
      end)) as value 
FROM transaction t 
GROUP BY t.user_id, t.symbol; 

如果type只對兩個值,可以簡化這:

SELECT t.user_id, t.symbol, 
     sum(case when t.type = 'SELL' then -t.volume else t.volume end) as total_volume, 
     sum(t.volume * t.unit_price * 
      (case when t.type = 'SELL' then -1 else 1 end) 
      end)) as value 
FROM transaction t 
GROUP BY t.user_id, t.symbol; 
+0

我寧願像\所有其他列引用一樣限定\'type \'的非限定引用。 ** + 10 **。案例的「搜索」形式... **'可以'買'時賣'然後'買'時可以使用'案例'。許多方法去皮膚貓。只是有些方法比其他方法要複雜得多。 – spencer7593

+0

有沒有簡單的方法,我也可以添加'Where total_volume!= 0'子句? – Edd

+1

@ Ed0906。 ..這將'在'group by'之後擁有total_volume <> 0'。 –