在SELECT中使用CASE的SQL查询不起作用

时间:2014-04-25 05:32:33

标签: php mysql sql

我有一个更大的复杂查询的这一部分:

SELECT SUM(pir.priceChange) AS CASE 
WHEN (SUM(pir.priceChange) > 0) THEN sellSum 
WHEN (SUM(pir.priceChange) < 0) THEN priceSum 
END

每当我尝试通过PDO将其传递给MySQL(MyISAM)时,它会抛出异常:

  

语法错误或访问冲突:1064 SQL语法中出错;查看与您的MySQL服务器版本对应的手册,以便在'(SELECT SUM(pir.priceChange)AS CASE WHEN(SUM(pir.priceChange)&gt; 0)THEN sellSu'第17行附近使用正确的语法

我想这与我试图错误地使用CASE语句这一事实有关。真的很想知道出了什么问题,提前谢谢。

编辑:我的完整查询(无任何情况编辑):

SELECT  pi.id AS id,
pi.type AS type,
pi.parValue AS rating,
pi.duration AS time,
countAmt.amt AS amtSold,
IFNULL(pii.pChange,
0) AS priceTotal,
0) AS costTotal,
IFNULL(pii.selfPrice,
0) AS costPrice,
(IFNULL(pii.sellSum,
0) - IFNULL(pii.selfPrice,
0)) AS profit,
countClose.amtClosed AS amtClosed
FROM salon.paymentInstrument as pi
(SELECT SUM(pir.priceChange) AS pChange,
SUM(pir.costChange) AS cChange,
(IFNULL(pir.priceChange,
0) - IFNULL(pir.costChange,
0)) AS selfPrice,
pii.paymentInstrumentID
FROM salon.paymentInstrumentRegister as pir
JOIN salon.paymentInstrumentItem as pii ON pir.paymentInstrumentItemID = pii.id
WHERE pir.date >= '2014-04-11'
AND pir.date <= '2014-04-25'
GROUP BY pii.paymentInstrumentID 
) as pii
(SELECT pii.paymentInstrumentID,
COUNT(*) AS amtClosed
FROM salon.paymentInstrumentItem as pii
WHERE pii.annulTime >= 2014-04-11
AND pii.annulTime <= 2014-04-25
AND pii.status <> "active"
GROUP BY pii.paymentInstrumentID 
) as countClose
(SELECT pii.paymentInstrumentID,
COUNT(*) AS amt
FROM salon.paymentInstrumentItem as pii
WHERE pii.startTime >= 2014-04-11
AND pii.startTime <= 2014-04-25
GROUP BY pii.paymentInstrumentID 
) as countAmt

抱歉格式不正确,它是用PHP动态生成的。我有一种感觉,我在查询的其他地方犯了一个错误。

2 个答案:

答案 0 :(得分:2)

尝试这种方式:

SELECT CASE WHEN SUM(pir.priceChange)>0 THEN SUM(pir.priceChange) END as SumPrice,
       CASE WHEN SUM(pir.priceChange)<0 THEN SUM(pir.priceChange) END as priceSum
FROM TableName

SQL Fiddle中的示例。

答案 1 :(得分:0)

试试这个:

SELECT CASE 
WHEN (SUM(pir.priceChange) > 0) THEN sellSum 
WHEN (SUM(pir.priceChange) < 0) THEN priceSum 
END