2012-12-18 106 views
0

我有我想轉換到一個視圖以下查詢:轉換交叉表查詢到視圖

SELECT 
    PartNum, 
    SUM(IF(DAYOFWEEK(DeliveryDate) = '2', value, NULL)) AS 'Mon', 
    SUM(IF(DAYOFWEEK(DeliveryDate) = '3', value, NULL)) AS 'Tue', 
    SUM(IF(DAYOFWEEK(DeliveryDate) = '4', value, NULL)) AS 'Wed', 
    SUM(IF(DAYOFWEEK(DeliveryDate) = '5', value, NULL)) AS 'Thu', 
    SUM(IF(DAYOFWEEK(DeliveryDate) = '6', value, NULL)) AS 'Fri', 
    SUM(IF(DAYOFWEEK(DeliveryDate) = '7', value, NULL)) AS 'Sat', 
    SUM(IF(DAYOFWEEK(DeliveryDate) = '1', value, NULL)) AS 'Sun', 
    SUM(IF(DeliveryDate > DATE_ADD(CURDATE(),INTERVAL 7 DAY), value, NULL)) AS 'Future' 
FROM (
    SELECT PartNum, DeliveryDate , SUM(Ordered) value FROM v_archived_items_due 
    GROUP BY PartNum, DeliveryDate 
    ) t 
    GROUP BY PartNum; 

當我嘗試將其保存爲一個觀點,我得到以下錯誤:

1349 - Views SELECT contains a subquery in the FROM clause.

該查詢本身工作正常。我怎麼把它變成一個視圖?

回答

0

MySQL不允許查看子查詢,所以沒有看到任何示例數據,看看如何在沒有subqyery的情況下重做這個。由於這是按預期工作,我會創造你的子查詢的視圖:

create view view1 as 
    SELECT PartNum, DeliveryDate , SUM(Ordered) value 
    FROM v_archived_items_due 
    GROUP BY PartNum, DeliveryDate; 

然後,只需調用查詢這樣的觀點:

SELECT 
    PartNum, 
    SUM(IF(DAYOFWEEK(DeliveryDate) = '2', value, NULL)) AS 'Mon', 
    SUM(IF(DAYOFWEEK(DeliveryDate) = '3', value, NULL)) AS 'Tue', 
    SUM(IF(DAYOFWEEK(DeliveryDate) = '4', value, NULL)) AS 'Wed', 
    SUM(IF(DAYOFWEEK(DeliveryDate) = '5', value, NULL)) AS 'Thu', 
    SUM(IF(DAYOFWEEK(DeliveryDate) = '6', value, NULL)) AS 'Fri', 
    SUM(IF(DAYOFWEEK(DeliveryDate) = '7', value, NULL)) AS 'Sat', 
    SUM(IF(DAYOFWEEK(DeliveryDate) = '1', value, NULL)) AS 'Sun', 
    SUM(IF(DeliveryDate > DATE_ADD(CURDATE(),INTERVAL 7 DAY), value, NULL)) AS 'Future' 
FROM view1 
GROUP BY PartNum; 
+0

非常感謝你們倆。 BF,你的解決方案就像一個魅力! – AlphaBase

+0

@ user1842670如果有任何答案有幫助,請務必通過答案左側的複選標記進行接受。 – Taryn