0

So I am doing homework for mysql class and I am having a hard time understanding why my code is bringing back no data, it runs but returns nothing when I know that data that meets the criteria exists. Please help. Here is my code:

SELECT vendor_id
     , SUM(invoice_total) AS invoice_gt
     , AVG(invoice_total) AS invoice_avg
     , COUNT(invoice_id) AS invoice_qty
  FROM invoices
 WHERE "invoice_avg" > 300
 GROUP 
    BY vendor_id
 ORDER 
    BY "invoice_avg" DESC
Strawberry
  • 33,750
  • 13
  • 40
  • 57
mildlylost
  • 57
  • 6
  • can u show some data that meet this criteria? – JayPeerachai Sep 28 '19 at 19:35
  • Yes, if I remove the WHERE "invoice_avg" > 300 I return 34 rows with data that includes values that are greater than 300 in the invoice_avg column – mildlylost Sep 28 '19 at 19:37
  • You need to use HAVING instead of WHERE. – Markus Zeller Sep 28 '19 at 19:38
  • 1
    `"invoice_avg"` is a string. It won't ever be greater than 300. Try removing the quotes (or use backticks as needed instead of double quotes). See https://stackoverflow.com/questions/11321491/when-to-use-single-quotes-double-quotes-and-backticks-in-mysql for more. – L. Scott Johnson Sep 28 '19 at 19:39
  • Note that depending on your settings for [ANSI_QUOTES](https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_ansi_quotes), `"invoice_avg"` will be treated as a constant string or column name. However - If `ANSI_QUOTES` were enabled, you should get an error message for this query. – Paul Spiegel Sep 29 '19 at 15:11

2 Answers2

0

Remove quotes and try

USE ap;
SELECT vendor_id, SUM(invoice_total) AS invoice_gt, AVG(invoice_total) AS 
invoice_avg, COUNT(invoice_id) AS invoice_qty
FROM invoices
WHERE invoice_avg > 300
GROUP BY vendor_id
ORDER BY invoice_avg DESC
Dhanush
  • 112
  • 7
0

You can't use an aggregated column in the WHERE clause.
Use it in a HAVING clause which is evaluated after the SELECT statement:

SELECT vendor_id, SUM(invoice_total) AS invoice_gt, AVG(invoice_total) AS invoice_avg, COUNT(invoice_id) AS invoice_qty
FROM invoices
GROUP BY vendor_id
HAVING invoice_avg > 300
ORDER BY invoice_avg DESC
forpas
  • 160,666
  • 10
  • 38
  • 76