Date balance in mysql

Asked

Viewed 128 times

-1

I have a table requests and would like to return to the following situation. select all orders of a current month idClient by summing the values of the same. type select * from pedidos where idCliente = id and dataPedido(search month type 10/2018) sum(valortotalPedido) I’m not getting because the date field in mysql is as follows 2018-10-01 22:02:01 or is standard format. I don’t know if I was clear but I appreciate anyone who can help

  • 1

    The Mysql field is perfect. Things work exactly in this format, what is missing is you use proper logic in comparison (which may eventually arise in the answers).

2 answers

2

To return the sum of values per client:

$mes = date('m');
$ano = date('Y');

SELECT sum(valortotalPedido) FROM pedidos
WHERE idCliente = $id and Month(dataPedido) = $mes and Year(dataPedido) = $ano

How the query uses the aggregation function sum, it will not be possible to return the list of requests consistently, since the "total valuePedido" field will be grouped.

1

Get the date you use Day/Month/Year convert to Year/Month/Day, take the year and month the date provides and put in query.

// Data recebida Dia/Mês/Ano
$data       = '01-11-2018 22:02:01';
// Converta a data para Ano/Mes/Dia
$data       = date('Y-m-d G:i:s', strtotime($data));
// Pegue o Mês da data
$mes        = date('m', strtotime($data));
// Pegue o Ano da data
$ano        = date('Y', strtotime($data));
$query  = "SELECT * FROM $this->table WHERE MONTH(data) = ':MES' AND YEAR(data) = ':ANO'";

Change the date format:

date('Y-m-d G:i:s', strtotime('01-10-2018 22:02:01'));

Return:

2018-10-01 22:02:01

More information: date strtotime

  • Thanks friend, based on your reply I got what I wanted as follows $mes = date(’m'); $ano = date('Y'); $query = "SELECT SUM(total valuePedido) AS total FROM $this->orders WHERE MONTH(dataPedido) = :data AND YEAR(dataPedido) = :year AND idCliente = :id";

  • You’re welcome, @Lucianodepaula

Browser other questions tagged

You are not signed in. Login or sign up in order to post.