2

以下は私が使用しているクエリです

SELECT 
  `names`, sum(cashin.amount) as amountin, 
  sum(cashout.amount) as amountout, 
  (sum(cashin.amount) - sum(cashout.amount)) as total 
FROM (`client`) 
INNER JOIN `cashin` ON `cashin`.`clientid`=`client`.`id` 
INNER JOIN `cashout` ON `cashout`.`clientid`=`client`.`id` 
WHERE (sum(cashin.amount) - sum(cashout.amount)) < 0 
GROUP BY `client`.`id`

問題は、エラーが発生することです:

Invalid use of group function

where 句の関数をフィールド エイリアスに置き換えて'total'も、エラーが発生します。

Unknown column total

このクエリはどのように修正できますか?

4

4 に答える 4

1

HAVINGの代わりに使用し、句の代わりに句を次のように句の前にWHERE置きます。GROUP BY namesGROUP BY idHAVING

SELECT 
  `names`, 
  sum(cashin.amount) as amountin, 
  sum(cashout.amount) as amountout, 
  (sum(cashin.amount) - sum(cashout.amount)) as total 
FROM client
INNER JOIN `cashin` ON `cashin`.`clientid`=`client`.`id` 
INNER JOIN `cashout` ON `cashout`.`clientid`=`client`.`id` 
GROUP BY names
HAVING (sum(cashin.amount) - sum(cashout.amount)) < 0 
于 2012-12-10T11:30:11.653 に答える
0

これのエイリアスを作成します

   (sum(cashin.amount) - sum(cashout.amount)) as total

合計として、なぜあなたはここでそれを使用しないのですか?

  WHERE (sum(cashin.amount) - sum(cashout.amount)) < 0

に置き換えます

     WHERE total < 0

この

 FROM (`client`) 

使用するだけ

  FROM `client`

この

  (sum(cashin.amount) - sum(cashout.amount)) as total  // line 4

に置き換えます

   (amountin - amountout) as total 

そしてそれはあなたのためにうまくいくでしょう。

于 2012-12-10T12:08:47.307 に答える
0

句を使用する代わりに、クエリをステートメントHAVINGでラップしてから、フィルタを句に配置できます。SELECTWHERE

select names,
  amountin,
  amountout,
  total
from
(
  SELECT 
    `names`, 
    sum(cashin.amount) as amountin, 
    sum(cashout.amount) as amountout, 
    (sum(cashin.amount) - sum(cashout.amount)) as total 
  FROM client
  INNER JOIN `cashin` ON `cashin`.`clientid`=`client`.`id` 
  INNER JOIN `cashout` ON `cashout`.`clientid`=`client`.`id` 
  GROUP BY names
) src
where total < 0
于 2012-12-10T11:33:07.647 に答える
0

これを試して ::

SELECT 
  `names`, 
  sum(cashin.amount) as amountin, 
  sum(cashout.amount) as amountout, 
  (sum(cashin.amount) - sum(cashout.amount)) as total 
FROM client
INNER JOIN `cashin` ON `cashin`.`clientid`=`client`.`id` 
INNER JOIN `cashout` ON `cashout`.`clientid`=`client`.`id` 
GROUP BY names
HAVING total < 0
于 2012-12-10T11:31:56.053 に答える