SQL Server分组但选择' top'日期

时间:2017-06-19 08:21:40

标签: sql-server

我在SQL服务器中有一个像这样的表(注意ID字段不是唯一的):

-----------------------------------
| ID | IsAdamBrown | DateComplete |
| 1  |     TRUE    | 2017-01-01   |
| 1  |     TRUE    | 2017-01-03   |
-----------------------------------

我想为表格中的所有唯一ID选择一行, 最新 ' DateComplete'该ID。

在这种情况下,我想要的输出是:

-----------------------------------
| ID | IsAdamBrown | DateComplete |
| 1  |     TRUE    | 2017-01-03   |
-----------------------------------

我试过了:

  SELECT DISTINCT DateComplete, ID, IsAdamBrown 
  FROM thisTable
  WHERE IsAdamBrown IS NOT NULL
  GROUP BY DateComplete, ID, IsAdamBrown
  ORDER BY DateComplete DESC

不幸的是,我仍然得到两个日期行。在MySQL中,我只按前两行分组,ORDER BY将确保DateComplete是最新的。 <{1}}字段与SELECT匹配的SQL服务器要求使这变得不可能。

如何使用最新的DateComplete为每个ID获取一行?

5 个答案:

答案 0 :(得分:2)

SELECT id,        isadambrown,        Max(datecomplete)AS DateComplete 来自这个表格 GROUP BY id,           isadambrown ORDER BY Max(datecomplete)DESC

答案 1 :(得分:1)

您可以GROUP BY MAX() DateComplete

前往 SELECT ID, IsAdamBrown, MAX(DateComplete) AS DateComplete FROM thisTable WHERE IsAdamBrown IS NOT NULL GROUP BY ID, IsAdamBrown ORDER BY MAX(DateComplete) DESC
{{1}}

答案 2 :(得分:0)

您可以使用LIMIT

  SELECT ID, IsAdamBrown, DateComplete
  FROM thisTable
  WHERE IsAdamBrown IS NOT NULL
  GROUP BY ID, IsAdamBrown
  ORDER BY DateComplete LIMIT 1

答案 3 :(得分:0)

你可以用它。我希望它对你有用。

SELECT ID, IsAdamBrown, DateComplete
  FROM thisTable a
  WHERE DateComplete IN 
(
SELECT MAX(DateComplete) FROM thisTable b WHERE a.ID = b.ID GROUP BY b.ID
) ORDER BY DateComplete DESC

答案 4 :(得分:0)

您可以使用ROW_NUMBER()根据ID和子查询进行分组,以获得唯一具有最近iscomplete的第一条记录。这将首先根据id和最近的iscomplete以及所有唯一ID的第一个结果对数据进行排序

SELECT X.ID, X.IsAdamBrown, X.DateComplete 
FROM ( SELECT ID, IsAdamBrown, DateComplete,ROW_NUMBER() OVER(PARTITION BY ID ORDER BY DateComplete DESC) RN
       FROM thisTable
       WHERE IsAdamBrown IS NOT NULL    ) X
WHERE X.RN=1