简体   繁体   English

1242-子查询在子查询中返回多于1行

[英]1242 - Subquery returns more than 1 row in subquery

I'm trying to get the total of pending amount of each staff. 我正在尝试获取每个员工的待处理总数。 The below query works fine: 下面的查询工作正常:

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

but when I try to add it as a subquery it gives me the error below: 但是当我尝试将其添加为子查询时,出现以下错误:

1242 - Subquery returns more than 1 row 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

any help will be appreciated.. 任何帮助将不胜感激..

Since your subquery returns more than one row (i expect that it will return a row for each class), you need do join your subquery in the from clause: 由于您的子查询返回了多行(我希望它将为每个类返回一行),因此您需要在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

It's pretty simple, really. 确实很简单。 Subqueries can only return one row. 子查询只能返回一行。 That's what the error message tells you. 这就是错误消息告诉您的内容。 The query you gave most likely returns more than one row (one for each class, in fact). 您提供的查询最有可能返回多行(实际上,每个类一个)。 Since you provide no output, I can only guess that this is true. 由于您没有提供输出,因此我只能猜测这是对的。

To fix it, you need to change that query to return one row. 要解决此问题,您需要更改该查询以返回一行。 Perhaps you get rid of the GROUP BY , or perhaps you pick the largest (or smallest) sum and return that. 也许您摆脱了GROUP BY ,或者您选择了最大(或最小)的总和并将其返回。 It's up to you based on your business requirements. 取决于您的业务需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM