SQL查询检查结果与同一个表中的其他行

时间:2017-08-20 12:37:31

标签: sql sql-server

我希望构建SQL查询以根据日期范围选择行,并且还需要其他列 以下是我的样本表

+----+--------------+--------------+--------------+--------------+
| id | CustomerID   | AccountID    |  DateFrom    |    DateTo    |
+----+--------------+--------------+--------------+--------------+
|  1 | C0001        | A0001        | 21/01/2016   | 28/01/2016   |
|  2 | C0001        | A0001        | 01/02/2016   | 08/02/2016   |
|  3 | C0002        | A0002        | 09/02/2016   | 16/02/2016   |
|  4 | C0002        | A0002        | 14/01/2016   | 21/01/2016   |
|  5 | C0003        | A0003        | 07/01/2016   | 14/01/2016   |
|  6 | C0003        | A0003        | 09/02/2016   | 16/02/2016   |
|  7 | C0004        | A0004        | 01/01/2016   | 07/01/2016   |
|  8 | C0004        | A0004        | 09/03/2016   | 16/03/2016   |
+----+--------------+--------------+--------------+--------------+

如果通过日期范围是从 01/02/2016 28/02/2016 ,那么我需要结果如下

+----+-------------+------------+--------------+--------------+-------------+
| id | CustomerID  | AccountID  |  DateFrom    |  DateTo      |  isPrevious |
+----+-------------+------------+--------------+--------------+-------------+
|  1 | C0001       | A0001      | 01/02/2016   |  08/02/2016  |    Yes      |
|  2 | C0002       | A0002      | 09/02/2016   |  16/02/2016  |    Yes      |
|  3 | C0003       | A0003      | 09/02/2016   |  16/02/2016  |    Yes      |
+----+-------------+------------+--------------+--------------+-------------+

2 个答案:

答案 0 :(得分:3)

这假设您希望数据完整包含且不与目标范围重叠。还假设您的行范围都没有相互重叠。

SELECT t1.*, 
       CASE WHEN (SELECT 1 
                  FROM yourTable t2
                  WHERE t2.DateFrom < t1.DateFrom
                    and t2.CustomerID  = t1.CustomerID  
                    and t2.AccountID = t1.AccountID ) IS NULL
            THEN 'No'
            ELSE 'Yes'
       END as isPrevious

FROM yourTable t1

WHERE DateFrom <= '2016-02-28' and
      DateTo >= '2016-02-01';

答案 1 :(得分:0)

如果我理解正确,这是一个简单的选择:

select t.*
from t
where DateFrom <= '2016-02-28' and
      DateTo >= '2016-02-01';

至少,这会在你描述时给出结果。