在嵌套的SQL中如何对值进行分组

时间:2019-02-14 15:08:47

标签: mysql sql

我有以下SQL

SELECT MAX(o.tax) as tax_value 
FROM offer AS o 
WHERE o.status in (1) 
GROUP BY(o.offer_no)

假设上述查询返回3条记录,但我想将这些记录加到另一个SQL中

SELECT SUM(SELECT MAX(o.tax) as tax_value 
FROM offer AS o 
WHERE o.status in (1) 
GROUP BY(o.offer_no))  as created

但这给我一个错误信息。我怎么解决这个问题。我想得到这些值的总和。

2 个答案:

答案 0 :(得分:1)

将其放在子查询中:

SELECT SUM(tax_value)
FROM (
    SELECT MAX(tax) AS tax_value
    FROM offer
    WHERE status = 1
    GROUP BY offer_no) x

答案 1 :(得分:0)

您可以使用“表表达式”:

select sum(x.tax_value) as tax_value
from ( -- table expression here acts as a table
  SELECT MAX(o.tax) as tax_value 
  FROM offer AS o 
  WHERE o.status in (1) 
  GROUP BY(o.offer_no)
) x