MySql组中的子查询

时间:2016-07-14 07:46:13

标签: mysql sql

我有一个问题:

SELECT round(addTime/qty, 0) AS col1,
       sum(qty) AS col2,
       cId AS Id
FROM MyTable
WHERE qty > 0
GROUP BY round(addTime/qty, 0), cId
ORDER BY round(addTime/qty, 0)

但我必须用

替换addTime
SUM(CASE WHEN qty = 1 THEN 1 ELSE DATEDIFF(second,startTime,endTime) END)/qty, 0)

当我这样做时:

SELECT round(SUM(case when qty = 1 then 1 else DATEDIFF(second,startTime,endTime) end)/qty, 0) AS col1,
sum(qty) AS col2,
cId
FROM MyTable
WHERE qty > 0
GROUP BY round(SUM(case when qty = 1 then 1 else
DATEDIFF(second,startTime,endTime) end)/qty, 0)/qty, 0), cId
ORDER BY round(SUM(case when qty = 1 then 1 else DATEDIFF(second,startTime,endTime) end)/qty, 0)/qty, 0)

我得到了

Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause.

我的想法是我可以将新查询用作变量,然后在我需要的地方使用它,但后来我遇到了MySql语法问题。

提前非常感谢!

2 个答案:

答案 0 :(得分:1)

尝试使用from子句中的子查询:

选择* from(从MyTable选择round(...)作为col1)作为tmp where ... Group by tmp.col1

Subqueries in from clause

答案 1 :(得分:1)

SELECT *
FROM (
    SELECT 
        round(SUM(case when qty = 1 then 1 else DATEDIFF(second, startTime,endTime) end)/qty, 0) AS col1, 
        sum(qty) AS col2, 
        cId
    FROM MyTable
    WHERE qty > 0
) AS t
GROUP BY t.col1, t.cId
ORDER BY t.col1

此外,我不确定,但您的DIFFTIME功能与MySQL DIFFTIME不同。