2013-08-19 61 views
0

嗨我有幀這個查詢,我遇到了這樣的錯誤 這樣我嘗試了很多,但沒有結果.i已修改查詢,然後它顯示另一個錯誤。
無法準備以下查詢
準備SQL語句時出錯。
我在mysql查詢中出錯?

SQL error #1:Syntax error: Encountered "MONTH" at line 4, column 46. 





SELECT distinct productline as StringFact,orderdate, 
SUM(CASE WHEN DATE(orderdate) between 
(DATE_FORMAT(DATE_ADD(orderdate,INTERVAL -12 MONTH),'%Y-m%-01')) 
AND (DATE_FORMAT(DATE_ADD(orderdate,INTERVAL -11 MONTH),'%Y-m%-01')) THEN BUY END)   AS  PREVYEAR, 

SUM(CASE WHEN DATE(orderdate) between 
(DATE_FORMAT(DATE_ADD(CURDATE(),INTERVAL 0 MONTH),'%Y-m%-01')) 
AND (DATE_FORMAT(DATE_ADD(orderdate,INTERVAL 0 MONTH),'%Y-m%-01')) THEN BUY END) AS  CURRENTMONTH, 

SUM(CASE WHEN DATE(orderdate) between 
(DATE_FORMAT(DATE_ADD(CURDATE(),INTERVAL -1 MONTH),'%Y-m%-01')) 
AND (DATE_FORMAT(DATE_ADD(orderdate,INTERVAL -1 MONTH),'%Y-m%-01')) THEN BUY END) AS LASTMONTH 

    from (select orderdate,productline as StringFact, 
    sum(QUANTITYINSTOCK + BUYPRICE) as BUY, 
    sum(QUANTITYORDERED * PRICEEACH) as MSRP 

    from customers, orders, orderdetails, products 
    where customers.customernumber = orders.customernumber 
    and orders.ordernumber = orderdetails.ordernumber 
    and orderdetails.productcode = products.productcode 
    Group By productline,orderdate 
) 
Group By productline,orderdate 
+3

的錯誤信息是不是我想它應該是sqlfiddle,但如果我沒看錯的MySQL需要別名每個子查詢。 所以,你可以把一個別名的子查詢,並嘗試再次執行? – Bren

+0

我已經嘗試過,它只顯示相同的錯誤...有什麼辦法可以做到這一點.. – jagan4040

+0

我認爲'%Y-%m%-01'應該是'%Y-%m-01',沒有%m%,[參考](http://www.w3schools.com/sql/func_date_format.asp) –

回答

0

的錯誤信息是不是我認爲它應該是。

什麼是你的mysql版本? 2)另一個問題是,您在外部查詢中選擇了「product_line」,但在子查詢中選擇了product_line作爲「StringFact」,這就是爲什麼outer_query不會在外部查詢能夠選擇product_line。

我改變了你的查詢如下,它沒有問題執行。

這裏是您查詢http://www.sqlfiddle.com/#!2/26218/6

SELECT distinct productline as StringFact,orderdate, 
SUM(CASE WHEN DATE(orderdate) between 
(DATE_FORMAT(DATE_ADD(orderdate,INTERVAL -12 MONTH),'%Y-m%-01')) 
AND (DATE_FORMAT(DATE_ADD(orderdate,INTERVAL -11 MONTH),'%Y-m%-01')) THEN BUY END)    AS  PREVYEAR, 

SUM(CASE WHEN DATE(orderdate) between 
(DATE_FORMAT(DATE_ADD(CURDATE(),INTERVAL 0 MONTH),'%Y-m%-01')) 
AND (DATE_FORMAT(DATE_ADD(orderdate,INTERVAL 0 MONTH),'%Y-m%-01')) THEN BUY END) AS   CURRENTMONTH, 

SUM(CASE WHEN DATE(orderdate) between 
(DATE_FORMAT(DATE_ADD(CURDATE(),INTERVAL -1 MONTH),'%Y-m%-01')) 
AND (DATE_FORMAT(DATE_ADD(orderdate,INTERVAL -1 MONTH),'%Y-m%-01')) THEN BUY END) AS LASTMONTH 

    from (select orderdate,productline , # removed as StringFact 
    sum(QUANTITYINSTOCK + BUYPRICE) as BUY, 
    sum(QUANTITYORDERED * PRICEEACH) as MSRP 

    from customers, orders, orderdetails, products 
    where customers.customernumber = orders.customernumber 
    and orders.ordernumber = orderdetails.ordernumber 
    and orderdetails.productcode = products.productcode 
    Group By productline,orderdate 
) t # You need to give an alias 
Group By productline,orderdate