从特定日期的数据库中选择记录

时间:2018-08-01 10:37:48

标签: sql sql-server

好,我有这个示例表:

+-------+--------+-----------+
| users | groups | startDate |
+-------+--------+-----------+
| Foo   | A      | 1 Aug 18  |
| Foo   | B      | 1 Jan 18  |
| Boo   | C      | 1 Jan 18  |
| Doo   | B      | 1 Jan 18  |
| Loo   | B      | 1 Sep 18  |
+-------+--------+-----------+

并且我要选择“ B组”用户的“ startDate”不高于今天,并且在最近的“ startDate”中也没有其他组的其他记录也不高于今天,因此正确的结果应该是: / p>

+-------+--------+-----------+
| users | groups | startDate |
+-------+--------+-----------+
| Doo   | B      | 1 Jan 18  |
+-------+--------+-----------+

我尝试了以下代码,但没有得到我所需要的:

DECLARE @StartDate date = '2018-08-01'
DECLARE @GroupID varchar(1) = 'B';
WITH CurrentUsers AS (SELECT users, groups, startDate, ROW_NUMBER() OVER(PARTITION BY users ORDER BY CASE WHEN startDate>@StartDate THEN 0 ELSE 1 END, ABS(DATEDIFF(DAY, @StartDate, startDate)) ASC) AS RowNum FROM usersTable) SELECT users FROM CurrentUsers WHERE groups=@GroupID AND RowNum = 1

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您似乎想要:

select user
from currentusers cu
group by user
having sum(case when groups = @GroupID then 1 else 0 end) > 0 and  -- in Group B
       max(startdate) < @StartDate;

编辑:

以上内容是基于误解。您想要今天活跃的人。我想你想要

WITH CurrentUsers AS (
      SELECT users, groups, startDate,
           ROW_NUMBER() OVER (PARTITION BY users
                              ORDER BY startDate DESC
                             ) as seqnum
      FROM usersTable
      WHERE startDate <= @StartDate
     )
SELECT users
FROM CurrentUsers
WHERE groups=@GroupID AND seqnum = 1;