本文介绍了TSQL仅显示第一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下TSQL查询:

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.

我如何得到它?

非常感谢!

推荐答案

在SQL Server中,您可以使用:

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

如果您需要使用 DISTINCT ,则可以使用:

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

甚至:

SELECT MAX(MyTable1.Date)
FROM MyTable1
INNER JOIN MyTable2
  ON MyTable1.Id = MyTable2.Id
WHERE Name = 'John'
--ORDER BY MyTable1.Date DESC

这篇关于TSQL仅显示第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 12:22