如何根据使用SQL Server选择的不同行(列)获取不同行

如何根据使用SQL Server选择的不同行(列)获取不同行,sql,sql-server,Sql,Sql Server,这可能很简单,但我在过去的一天里一直在搜索和尝试,但我的解决方案不起作用 我的数据表如下所示: SprintID, Start_Date, End_Date -------------------------------------------------------------- S100 2019-01-01 08:00:16.793 2019-01-10 06:59:00.000 S101 2019-01-11 08:00:1

这可能很简单,但我在过去的一天里一直在搜索和尝试,但我的解决方案不起作用

我的数据表如下所示:

SprintID, Start_Date,                  End_Date
--------------------------------------------------------------
S100      2019-01-01 08:00:16.793      2019-01-10 06:59:00.000
S101      2019-01-11 08:00:19.793      2019-01-20 06:59:00.000
S101      2019-01-11 09:00:16.793      2019-01-20 07:14:00.000
S101      2019-01-11 11:00:16.793      2019-01-20 08:32:00.000
S102      2019-01-21 08:00:16.793      2019-01-30 09:19:00.000
S102      2019-01-21 09:45:16.793      2019-01-30 06:59:00.000
...
请注意,在上面的数据中,我们可以看到开始日期和结束日期是同一天,但时间不同

我想要什么

我要寻找的是SprintID的一个单独/不同的值,它具有相应的开始日期和结束日期

我做了什么

我使用了以下代码,但它不做我例外的事情:

方法1

方法2


您可以使用窗口功能:

select d.*
from (select d.*,
             row_number() over (partition by sprintid order by start_date) as seqnum
      from data_table dt
    ) d
where seqnum = 1;

上面返回一行最早的开始日期。但是,可以通过调整顺序来控制所需的行。newid的表达式顺序返回一个随机行。

您可以使用窗口函数:

select d.*
from (select d.*,
             row_number() over (partition by sprintid order by start_date) as seqnum
      from data_table dt
    ) d
where seqnum = 1;
上面返回一行最早的开始日期。但是,可以通过调整顺序来控制所需的行。newid的表达式顺序返回一个随机行。

您可以使用NOT EXISTS,如下所示:

SELECT SprintID, Start_Date, End_Date
  FROM data_table t
 Where not exists 
       (Select 1 from data_table tt
         Where t.SprintID = tt.sprint_id And tt.start_date < t.start_date)
您可以按如下方式使用“不存在”:

SELECT SprintID, Start_Date, End_Date
  FROM data_table t
 Where not exists 
       (Select 1 from data_table tt
         Where t.SprintID = tt.sprint_id And tt.start_date < t.start_date)

谢谢你写的答案。它按预期工作。您知道distinctSprintID没有选择其他列的单个值的原因吗?@floss。distinct不是一个函数。select distinct是一个子句,其中distinct应用于所有列。感谢您撰写答案。它按预期工作。您知道distinctSprintID没有选择其他列的单个值的原因吗?@floss。distinct不是一个函数。select distinct是一个子句,其中distinct应用于所有列。
SELECT SprintID, Start_Date, End_Date
  FROM data_table t
 Where not exists 
       (Select 1 from data_table tt
         Where t.SprintID = tt.sprint_id And tt.start_date < t.start_date)