V
V
Vladimir Kai2017-04-04 16:29:36
MySQL
Vladimir Kai, 2017-04-04 16:29:36

How to convert DateTime to Date to group by date in SQL query - DELPHI?

Good afternoon dear experts!
I came across a problem with grouping SQL query results by date.
Table structure:
id - order number;
price - total cost;
date_insert - order date; - DateTime type I form
a request to calculate the average check and the number of orders:

SELECT id, date_insert, SUM(price), AVG(price), COUNT(id)
FROM b_sale_order
WHERE (canceled = 'N') AND (date_insert BETWEEN :StartD AND :EndD)
ORDER BY date_insert
GROUP BY date_insert

The grouping itself is not performed, since the request will fail with an error in grouping by the Date field.
I read that the problem is that I have a data type for this DateTime field, and not a simple Date.
And it is required to convert or discard part of the record over time.
How to do this to get a correct SQL_query grouped by the Date field?
The data will need to be driven into TeeChart, so there is no way without grouping..

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kai, 2017-04-06
@gold_dezmor

Actually everything works.
Here is the final query:

SELECT date_format(date_insert, "%Y.%m.%d") as Date, Sum(price), AVG(price) as SrCheck
FROM b_sale_order 
WHERE (canceled = 'N') AND (date_insert BETWEEN '2017.01.01' AND '2017.01.31') 
GROUP BY Date 
ORDER BY Date

R
Rsa97, 2017-04-04
@Rsa97

The error is that ORDER BY and GROUP BY must go in reverse order.
To group by date:

SELECT DATE(`date_insert`) AS `date`, SUM(`price`), AVG(`price`), COUNT(*)
  FROM `b_sale_order`
  WHERE (`canceled` = 'N') AND (`date_insert` BETWEEN :StartD AND :EndD)
  GROUP BY `date`
  ORDER BY `date`

It is useless to choose `id`, it will be taken from the first line in the group. The index in GROUP BY and ORDER BY will not work, since it is not the field value that is used, but a function from it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question