I am trying to get a count of the below-noted SQL query. It will output the max value of the scan_freq column and I want to get a count of the rows of it. eg: The below query returned 1096
SELECT barcode, MAX(scan_freq)
FROM dr_scan
GROUP BY barcode
Usually, I can get a count of the dr_scan table by this query
SELECT COUNT(*) as total FROM dr_scan
So I want to do the same for the below query (count how many raws returned)
SELECT barcode, MAX(scan_freq)
FROM dr_scan
GROUP BY barcode
I tried this and it will not be giving the output I expected
SELECT COUNT(*) AS total, barcode, MAX(scan_freq)
FROM dr_scan
GROUP BY barcode
2
Answers
The number of rows returned by a query with
GROUP BY column
without aWHERE
,HAVING
orLIMIT
clause is simply the number ofDISTINCT
values of that column. So you can get the result you want by:If you have clauses which may restrict some rows from the output, you can do this the hard way by using your query as a subquery:
or a CTE if you’re using MySQL 8+
Or you can get all the data and the total row count at the same time using window functions in MySQL 8+
Demo on dbfiddle.uk