Create a grouped query by month

Asked

Viewed 35 times

0

I have a field in my database (dt_nf) that is DATE type. I would like to do a query that groups not by date, but by month and year, but I’m not getting it. My code is like this:

SELECT 
Sum(sjy_vendas.qtv) AS qt, 
Sum(sjy_vendas.rprd) AS rec, 
Sum(rprd-tprd-vlr_compra) AS lucro
FROM sjy_type 
INNER JOIN sjy_empresas 
INNER JOIN sjy_vendas ON sjy_empresas.id_empresa = sjy_vendas.empresa
AND sjy_type.id_tipo = sjy_vendas.tipo
WHERE sjy_type.dep='1' 
AND sjy_empresas.grupo='$grupo' 
AND sjy_vendas.dt_nf BETWEEN '$inicio' AND '$final'
AND sjy_vendas.empresa LIKE '$emp'
GROUP BY MONTH(sjy_vendas.dt_nf) AS dt_nf
ORDER BY sjy_vendas.dt_nf

2 answers

2


there are two ways to do follow the ex:

GROUP BY DATE_FORMAT(sjy_vendas.dt_nf,'%Y-%m')

or else you make a month and year Xtract of the date field like this

SELECT EXTRACT(YEAR_MONTH FROM sjy_vendas.dt_nf) mesano 
    FROM ...

and group by will stay

GROUP BY mesano 

0

Good morning. It seems to me that if you want to group by the two variables you must have them in the group by and have them as a pillar in select, might be something like:

SELECT 
Sum(sjy_vendas.qtv) AS qt, 
Sum(sjy_vendas.rprd) AS rec, 
Sum(rprd-tprd-vlr_compra) AS lucro
concat(MONTH(sjy_vendas.dt_nf) , '/',YEAR(sjy_vendas.dt_nf)) as mesAno
...
GROUP BY concat(MONTH(sjy_vendas.dt_nf) , '/',YEAR(sjy_vendas.dt_nf))
  • Thank you for the reply Ana, but it has not yet worked. You are giving the following error: "Fatal error: Call to a Member Function fetchAll() on a non-object in D: xampp htdocs n_kurma pages head.php on line 456"

  • 1

    This error doesn’t seem to be related to the query, you tried the query outside of php and it doesn’t work? what I was saying is that you have to have at least the field you want to group into select.

Browser other questions tagged

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