1

我有 2 个独立的查询,它们正在计算给定节日的总收入/支出。IN/OUT 由 ENUM 值给出(见下文)。 在此处输入图像描述 在此处输入图像描述

如果我独立运行查询,它会根据所选的payment_type IN 或 OUT 给出正确的 SUM 输出。我的问题是,当我尝试将它们组合在一个查询中以使 IN/OUT 有 2 个单独的列时,如下所示。

在此处输入图像描述

我在 MySQL “操作数应包含 1 列”中有错误。在我做了一些研究之后,我相信子查询是错误的,但我不太确定如何解决它。

在此先感谢您的帮助...

总计

SELECT
    SUM(`payment`.`pmt_amount`) AS `TOTAL IN`
    , `payment`.`pmt_type`
    , `festival`.`id_festival`
FROM
    payment
    INNER JOIN festival
        ON (`payment`.`id_festival` = `festival`.`id_festival`)
WHERE (`payment`.`pmt_type` LIKE '%IN'
    AND `festival`.`id_festival` = 1);

在此处输入图像描述

并且完全出局

SELECT
    SUM(`payment`.`pmt_amount`) AS `TOTAL OUT`
    , `payment`.`pmt_type`
    , `festival`.`id_festival`
FROM
    payment
    INNER JOIN festival
        ON (`payment`.`id_festival` = `festival`.`id_festival`)
WHERE (`payment`.`pmt_type` LIKE '%OUT'
    AND `festival`.`id_festival` = 1);

在此处输入图像描述

结合

SELECT
  festival.id_festival,
  payment.pmt_amount,
  payment.pmt_type,
  (SELECT
      payment.pmt_type,
      SUM(payment.pmt_amount) AS `TOTAL OUT`
    FROM payment
    WHERE payment.pmt_type LIKE '%OUT'),
  (SELECT
      payment.pmt_type,
      SUM(payment.pmt_amount) AS `TOTAL IN`
    FROM payment
    WHERE payment.pmt_type LIKE '%IN')
FROM payment
  INNER JOIN festival
    ON payment.pmt_amount = festival.id_festival
WHERE festival.id_festival = 1

在此处输入图像描述

4

2 回答 2

1

您的子查询必须返回only one column,但您的查询正在返回two column,这是错误的尝试下面提到的查询:

SELECT
  festival.id_festival,
  payment.pmt_amount,
  payment.pmt_type,
  (SELECT
      SUM(payment.pmt_amount) AS `TOTAL OUT`
    FROM payment
    WHERE payment.pmt_type LIKE '%OUT') AS `TOTAL OUT`,
  (SELECT
      SUM(payment.pmt_amount) AS `TOTAL IN`
    FROM payment
    WHERE payment.pmt_type LIKE '%IN') AS `TOTAL IN`
FROM payment
  INNER JOIN festival
    ON payment.pmt_amount = festival.id_festival
WHERE festival.id_festival = 1
于 2018-04-07T10:34:53.230 回答
1

您可能只想在这里使用条件聚合:

SELECT
    f.id_festival,
    SUM(CASE WHEN p.pmt_type = 'Payment IN'  THEN p.pmt_amount ELSE 0 END) AS `TOTAL IN`,
    SUM(CASE WHEN p.pmt_type = 'Payment OUT' THEN p.pmt_amount ELSE 0 END) AS `TOTAL OUT`
FROM festival f
INNER JOIN payment p
    ON p.id_festival = f.id_festival
WHERE f.id_festival = 1
GROUP BY
    f.id_festival;

请注意,您的查询仅查看一个节日,但表达这一点的正确方法是 via,GROUP BY即使我们只想在输出中保留一个组。

于 2018-04-07T10:40:36.783 回答