How to select only 1 record per month with SQL

Asked

Viewed 78 times

1

I have a sales chart and would like to select customers' sales, but if the customer made more than one sale per month, I would like you to bring the oldest just, how could I do that?

I don’t have an SQL code to provide because I don’t know where to start, but I have the table in question:

inserir a descrição da imagem aqui

How I wish it was the return:

inserir a descrição da imagem aqui

Notice that line 2 is gone, because the customer "João" made 2 purchases in January and brought only the oldest purchase of it.

I’m just studying, these tables are just fictitious.

  • The oldest purchase of the month of January of Joseph would not be day 2?

  • 1

    @Virgilionovic In the case the purchase of the day 02/01 is the most recent, since it is closer to the current day, so the day 01/01 is the oldest of him.

  • I got it, I made an example!

1 answer

2


The way I understand it if you want the minimum value of the date per month (which is the oldest purchase) of a given name, example:

SELECT t1.id, 
    t1.nome,
    t1.data_compra, 
    t1.valor_compra 
FROM Compras t1
INNER JOIN (SELECT nome, MONTH(data_compra) as m, 
            MIN(data_compra) as c FROM Compras t2   
            GROUP BY nome, MONTH(data_compra)) AS t2 
  ON t1.nome = t2.nome AND t1.data_compra = t2.c

See online example

I made based on the two tables and with a INNER JOIN brought the most recent values by name, month and date.

  • 1

    Before the change p/ put the INNER JOIN I had already solved my problem, now I have another problem, it is not related to the theme of this question, I will try to solve alone, if I fail, I will come back here in Stackoverflow. Thank you so much for your help Virgilio.

Browser other questions tagged

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