简体   繁体   中英

mysql use logic in where clause + invalid use of group function

I have the below mysql query that outputs the below image:

select
  v.invoicenumber,
  v.invoicedate,
  v.haulier,
  v.transporttype,
  count(v.loadnumber) as totalloads,
  sum(v.cost) as totalcost, 
  concat(SUM(if(invoiceapproved = 'yes', 1, 0)),' / ',count(v.loadnumber)) AS count,  SUM(if(invoiceapproved = 'yes', 1, 0)) as approved
from v2loads v  
  where v.invoiced='yes'   
  group by invoicenumber

在此处输入图片说明 This query excutes 100%.

what I want to do is filter out any rows / data where the count is 100%. in the example output I want to filter out invoice 16 as it is 2/2 and 100%. so where

 count(v.loadnumber) <> SUM(if(invoiceapproved = 'yes', 1, 0))

if I add this logic into the where clause it fails with error invalid use of group function. so below code does not work:

select v.invoicenumber,
  v.invoicedate,
  v.haulier,
  v.transporttype,
  count(v.loadnumber) as totalloads,
  sum(v.cost) as totalcost, 
  concat(SUM(if(invoiceapproved = 'yes', 1, 0)),' / ',count(v.loadnumber)) AS count, 
  SUM(if(invoiceapproved = 'yes', 1, 0)) as approved 
from v2loads v  
  where v.invoiced='yes' and 
  (count(v.loadnumber))<>(SUM(if(invoiceapproved = 'yes', 1, 0)))  
  group by invoicenumber

I got the following error:

error is #1111 - Invalid use of group function.

Any advice appreciated as always.

You can do this:

SELECT 
  *,
  CONCAT(approved, ' / ', totalloads) AS count, 
FROM
(
    SELECT
      v.invoicenumber,
      v.invoicedate,
      v.haulier,
      v.transporttype,
      COUNT(v.loadnumber)                    AS totalloads,
      SUM(v.cost)                            AS totalcost, 
      SUM(if(invoiceapproved = 'yes', 1, 0)) As approved 
    FROM v2loads v  
    WHERE v.invoiced='yes'
    GROUP BY invoicenumber
) t
WHERE totalloads <> approved;
select v.invoicenumber,
v.invoicedate,
v.haulier,
v.transporttype,
count(v.loadnumber) as totalloads,
sum(v.cost) as totalcost, 
concat(SUM(if(invoiceapproved = 'yes', 1, 0)),' / ',count(v.loadnumber)) AS count,
SUM(if(invoiceapproved = 'yes', 1, 0)) as approved  
from v2loads v 
where v.invoiced='yes'
group by invoicenumber 
having (count(v.loadnumber))<>(SUM(if(invoiceapproved = 'yes', 1, 0)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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