Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL show only first row

Tags:

tsql

select

limit

I have the following TSQL query:

SELECT DISTINCT MyTable1.Date
  FROM MyTable1 
INNER JOIN MyTable2 
ON MyTable1.Id = MyTable2.Id
WHERE Name = 'John' ORDER BY MyTable1.Date DESC

It retrieves a long list of Dates, but I only need the first one, the one in the first row.

How can I get it?

Thanks a ton!

like image 734
ADM Avatar asked Oct 02 '12 10:10

ADM


People also ask

How do I show only one row in SQL?

While the table name is selected type CTRL + 3 and you will notice that the query will run and will return a single row as a resultset. Now developer just has to select the table name and click on CTRL + 3 or your preferred shortcut key and you will be able to see a single row from your table.

How do I SELECT the first row from multiple records in SQL?

To do that, you can use the ROW_NUMBER() function. In OVER() , you specify the groups into which the rows should be divided ( PARTITION BY ) and the order in which the numbers should be assigned to the rows ( ORDER BY ).

How do I SELECT the last 3 rows in SQL?

I want to select the last 3 rows of an sql table. I know I should use SELECT * FROM table ORDER BY DESC LIMIT 3 , but the problem with this code is that it selects the rows from the end. For example, it selects 30, then 29, then 28.


1 Answers

In SQL Server you can use TOP:

SELECT TOP 1 MyTable1.Date
FROM MyTable1 
INNER JOIN MyTable2 
  ON MyTable1.Id = MyTable2.Id
WHERE Name = 'John' 
ORDER BY MyTable1.Date DESC

If you need to use DISTINCT, then you can use:

SELECT TOP 1 x.Date
FROM
(
   SELECT DISTINCT MyTable1.Date
   FROM MyTable1 
   INNER JOIN MyTable2 
     ON MyTable1.Id = MyTable2.Id
    WHERE Name = 'John' 
) x
ORDER BY x.Date DESC

Or even:

SELECT MAX(MyTable1.Date)
FROM MyTable1 
INNER JOIN MyTable2 
  ON MyTable1.Id = MyTable2.Id
WHERE Name = 'John' 
--ORDER BY MyTable1.Date DESC
like image 83
Taryn Avatar answered Oct 15 '22 15:10

Taryn