0

hi i have frame this query and i encountered a error like this.i have tried many but no result .i have modified query then its showing another error.
Failed to prepare the following query
Error preparing SQL statement.

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
4

1 回答 1

0

错误消息不是我认为应该的。

你的mysql版本是多少?

1)您应该给子查询一个别名 2)另一个问题是,您在外部查询中选择了“product_line”,但在子查询中将 product_line 选择为“StringFact”,这就是为什么 outer_query 将无法选择 product_line .

我将您的查询更改如下,它执行没有问题。

这是您查询的 sqlfiddle 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
于 2013-08-19T08:09:41.093 回答