161k views
2 votes
Explain (in plain English) what each line (line by line) of the query below does. SELECT vendor_state, vendor_city, vendor_name, COUNT(*) AS invoice_qty, AVG(invoice_total) AS invoice_average FROM invoices JOIN vendors ON invoices.vendor_id = vendors.vendor_id WHERE vendor_state < 'e' GROUP BY vendor_state, vendor_city, vendor_name HAVING SUM(invoice_total) > 500 ORDER BY vendor_state, vendor_city, vendor_name

1 Answer

7 votes

Final Answer:

The SQL query retrieves specific columns (vendor_state, vendor_city, vendor_name), and additional calculated values (COUNT(*) as invoice_qty and AVG(invoice_total) as invoice_average) from the invoices and vendors tables. It filters the results to include only records where the vendor_state is alphabetically before 'e', groups the data by vendor state, city, and name, and further filters by the total invoice amount (SUM(invoice_total)) being greater than 500. The final result is then ordered by vendor_state, vendor_city, and vendor_name.

Step-by-step explanation:

SELECT vendor_state, vendor_city, vendor_name, COUNT() AS invoice_qty, AVG(invoice_total) AS invoice_average: This line specifies the columns to be retrieved from the tables (vendor_state, vendor_city, vendor_name) and includes calculated values (COUNT() as invoice_qty and AVG(invoice_total) as invoice_average).

FROM invoices JOIN vendors ON invoices.vendor_id = vendors.vendor_id: This line indicates that data is being retrieved from the invoices and vendors tables, and it specifies how the tables are joined using the common column vendor_id.

WHERE vendor_state < 'e': This line filters the results to include only records where the vendor_state is alphabetically before 'e'.

GROUP BY vendor_state, vendor_city, vendor_name: This line groups the data based on the specified columns (vendor_state, vendor_city, vendor_name), creating subsets for each unique combination of these values.

HAVING SUM(invoice_total) > 500: This line filters the grouped data, including only those groups where the total sum of invoice_total is greater than 500.

ORDER BY vendor_state, vendor_city, vendor_name: This line sorts the final result set in ascending order based on vendor_state, vendor_city, and vendor_name.

User Nevenoe
by
7.9k points