Select in Sql Server

Asked

Viewed 183 times

0

Good morning. I have a table with columns Version, Updated, LastChanged. I want to make a query to select the highest version value, with the respective LastChanged, corresponding to Updated = 1;

I did it like this, but it didn’t work.

select Max(Version), LastChanged from BMTDatabaseUpdate where Updated=1 
  • Could you elaborate on what you need, including posting data samples and the expected result? The phrase " select the highest value of the version, with the respective Lastchanged" can generate different interpretations...

  • For the same value of Version there can be more than one line, varying the value of Lastchanged?

2 answers

1

The statement leaves open whether, for the highest value of Version, it should return all lines (if there is more than one) or whether it should get the highest value for the pair (Version, Lastchanged).

Considering the second premise, evaluate the following code:

-- código #1
with cteSeq as (
SELECT Version, LastChanged,
       Seq= row_number() over(order by Version desc, LastChanged desc)
  from BMTDatabaseUpdate
   where Updated = 1
)
SELECT Version, LastChanged
  from cteSeq
  where Seq = 1;

0

There are several alternatives to get the desired result. Here are three alternatives.

The first using a "Function window":

SELECT *
  FROM
(
    SELECT Version, 
           LastChanged,
           ROW_NUMBER() OVER (ORDER BY Version DESC, LastChanged DESC) RN
      FROM BMTDatabaseUpdate  
     WHERE Updated = 1  
) V
WHERE RN = 1

The second using a sub-query:

SELECT BMT.Version,
       MAX(BMT.LastChanged) LastChanged,
       BMT.Updated
  FROM BMTDatabaseUpdate BMT
 INNER JOIN 
 (
     SELECT MAX(Version) MVersion
       FROM BMTDatabaseUpdate
      WHERE Updated = 1
 ) MaiorVersao
   ON MaiorVersao.MVersion= BMT.Version
 WHERE BMT.Updated = 1 
 GROUP BY BMT.Version
  • 1

    The statement of what Ana Carvalho asks seems incomplete, and may generate different interpretations and suggestions. I have posted a comment to her, asking her to clarify what she is asking for and so we can post specific solutions.

Browser other questions tagged

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