0

我正在尝试获取每个员工的待处理金额总数。以下查询工作正常:

SELECT SUM(amount) 
FROM pending
WHERE MONTH < DATE_SUB(curdate() , INTERVAL 1 MONTH) 
GROUP BY class

但是当我尝试将它添加为子查询时,它给了我以下错误:

1242 - 子查询返回多于 1 行

SELECT
  (period_diff(date_format(now(), '%Y%m'),
     date_format(MONTH, '%Y%m'))) AS months,
  pending.amount,
  pending.admission_numb,
  pending.month,
  staff.name,
  staff.class, (
    SELECT SUM(amount) 
    FROM pending
    WHERE MONTH < DATE_SUB(curdate(), INTERVAL 1 MONTH) 
    GROUP BY class
  )
FROM
  pending JOIN staff
  ON pending.admission_numb = staff.admission
GROUP BY admission
ORDER BY CAST( staff.class AS UNSIGNED ) , staff.class

任何帮助将不胜感激..

4

2 回答 2

1

由于您的子查询返回不止一行(我希望它会为每个类返回一行),您需要在 from 子句中加入您的子查询:

SELECT
  (period_diff(date_format(now(), '%Y%m'), date_format(MONTH, '%Y%m'))) AS months,
  pending.amount,
  pending.admission_numb,
  pending.month,
  staff.name,
  staff.class,
  sums.tot
FROM
  pending JOIN staff ON pending.admission_numb = staff.admission
  JOIN  (
    SELECT class, SUM(amount) as tot 
    FROM pending
    WHERE MONTH < DATE_SUB(curdate(), INTERVAL 1 MONTH)
    GROUP BY class
  ) sums on staff.class = sums.class
GROUP BY admission
ORDER BY CAST( staff.class AS UNSIGNED ) , staff.class
于 2012-11-25T18:03:52.657 回答
0

这很简单,真的。子查询只能返回一行。这就是错误消息告诉您的内容。您提供的查询很可能返回不止一行(实际上每个类一个)。由于您没有提供任何输出,我只能猜测这是真的。

要修复它,您需要更改该查询以返回一行。也许您摆脱了GROUP BY,或者您选择了最大(或最小)的总和并将其返回。这取决于您的业务需求。

于 2012-11-25T17:56:34.697 回答