SQL查询中的语法错误:意外的“SUM”(总和)

时间:2017-12-04 10:07:52

标签: mysql sql

我试图运行以下查询,我收到以下错误:

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近'sum(sl.duration)作为持续时间,sum(sl.quantity_loss)为   quantity_loss'

SELECT 
   lr.uid AS loss_reason_uid,
   gl.uid AS gl_uid,
   lt.uid AS lt_uid,
   SUM(sl.duration * b.marginal_value_downtime) AS value_loss where en.state = 'downtime',
   SUM(sl.quantity_loss * p.marginal_value) as value_loss where en.state != 'downtime',
   SUM(sl.duration) AS duration,
   SUM(sl.quantity_loss) AS quantity_loss,
   COUNT(*) AS count
FROM
    sub_losses AS sl

知道为什么会出现这种语法错误吗?

2 个答案:

答案 0 :(得分:0)

尝试使用:除了以上评论之外,不允许在一个查询块中多次使用相同的ALIASCOLUMN NAME,因此我已经{{1制作是独一无二的。

value_loss1

答案 1 :(得分:0)

这对我有用。感谢@HoneyBadger的指导。

SELECT 
    lr.uid AS loss_reason_uid,
        gl.uid AS gl_uid,
        lt.uid AS lt_uid,
        SUM(CASE WHEN en.state = 'downtime' THEN sl.duration * b.marginal_value_downtime ELSE sl.quantity_loss * p.marginal_value END) AS value_loss,
        SUM(sl.duration) AS duration,
        SUM(sl.quantity_loss) AS quantity_loss,
        COUNT(*) AS count
FROM
    sub_losses AS sl