delete repeated values sql server

2

I have a problem in a sql server query ... I have this table where I need to delete repeated values (those marked in blue) due to the last column ('hh''mm') and try the DISTINCT but even so he shows them to me

I do not know if I made myself understood, I hope you can help me ... this is the query

SELECT DISTINCT
n1,
n2, CONVERT (
    CHAR (10),
    maq_fechahora,
    108
) AS maq_fechahora, CONVERT (
    CHAR (5),
    maq_fechahora,
    108
) AS minu FROM
maq_equipos WHERE
maq_id = '020' AND CAST (maq_fechahora AS DATE) = '2018-10-17' AND maq_tip = 2 ORDER BY maq_fechahora ASC
    
asked by Milan 26.10.2018 в 20:46
source

2 answers

3

Basically, you want to stay with only one reading per minute, for the example you show, if you have two rows for the same minute, you want to keep the first one of them chronologically speaking.

A simple way to solve it is to generate a numerator for all rows by ROW_NUMBER() , with the particularity that will restart every minute: PARTITION BY LEFT(CONVERT(VARCHAR, maq_fechahora, 121), 16) , so we finally put everything in a subquery and only recover the rows where this counter is 1.

SELECT  *
    FROM (
        SELECT  n1,
            n2,
            ROW_NUMBER() OVER (PARTITION BY LEFT(CONVERT(VARCHAR, maq_fechahora, 121), 16) ORDER BY maq_fechahora) RN
            FROM    maq_equipos 
            WHERE   maq_id = '020' 
                AND CAST(maq_fechahora AS DATE) = '2018-10-17' 
                AND maq_tip = 2
    ) T
    WHERE RN = 1
    
answered by 26.10.2018 / 21:52
source
2

If you do not care which data is displayed for the other columns, you can group by the column that shows hh: mm and apply some function that returns a value on the others, such as min() or max() , for example:

SELECT   min(n1) n1
       , min(n2) n2
       , min(convert(char(10), maq_fechahora, 108)) AS maq_fechahora
       , convert(char(5), maq_fechahora, 108) AS minu 
  FROM maq_equipos 
 WHERE maq_id = '020' 
   AND CAST (maq_fechahora AS DATE) = '20181017' 
   AND maq_tip = 2 
 group by convert(char(5), maq_fechahora, 108) 
 ORDER BY convert(char(5), maq_fechahora, 108) ASC

In this case, it is clear that I am not deleting entire rows, but showing some value for them, this implies that a value of the first row could be shown in a column, and a value of the second row in the other column. This is because I am using the min() function that will simply return the smallest value. You can also use max() , or others like avg() , etc.

    
answered by 26.10.2018 в 22:35