A
A
Alex May2018-02-20 18:43:31
MySQL
Alex May, 2018-02-20 18:43:31

Mysql query with COUNT, SUBTOTAL and GRANDTOTAL - how to build?

Without using PHP
There is a table of visits, only 4 columns - timestamp, ip, useragent, daynumber
Please tell me how to build a query using MySQL (extensions are allowed) so that in the resulting output, in addition to the data, there are SUBTOTAL rows (number of rows) and GRANDTOTAL. Count subtotals - by the number of rows with a single identifier daynumber
I.e. something like this output is needed 5a8c41c58bd90387753848.png(see the picture)
Please save me - in PHP it turns out very ugly when you can do everything using SQL ))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
ivankomolin, 2018-02-27
@alexmay

Of course, you can extract all this data from mysql using sql, but not in this form, you still have to process them to get the look you have. And the request to the mysql server itself will not be optimal and will consume resources when executed.
The ideal solution to the problem in this case is to get all the data using sql with one simple query, and only then bring it into the desired form in php.
Well, if you really want to, then here's an example of how to get all the necessary data:

(SELECT
  timestamp, 
  ip, 
  useragent, 
  daynumber, 
  count(*) as total
FROM 
  table
GROUP BY 
  daynumber
)
UNION
(SELECT
  '' as timestamp,
  '' as ip, 
  '' as useragent, 
  '' as daynumber, 
  count(*) as total
FROM 
  table
)

The result will be a table, the last column of which will show the subtotal of the current daynumber, and the last row will show GRANDTOTAL

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question