sql - 如何根据出现的列序列提取行

标签 sql sql-server

我需要使用日期列提取与在“Out”之前出现的类型列中具有“In”的各自 Id 关联的所有行。在提供的数据中,只有 ID 1 和 2 会通过测试。 测试数据如下:

CREATE TABLE #Table (
id INT,
[type] varchar(25),
[Dates] Date)

INSERT INTO #Table
VALUES (1, 'In', '2018-10-01'),
 (1, 'In', '2018-11-01'),
 (1, 'Out', '2018-12-01'),
 (2, 'In', '2018-10-01'),
 (2, 'Out', '2018-11-01'),
 (2, 'In', '2018-12-01'),
 (3, 'Out', '2018-10-01'),
 (3, 'In', '2018-11-01')

输出应该是这样的:

+----+------+------------+
| id | type |    date    |
+----+------+------------+
|  1 | In   | 2018-10-01 |
|  1 | In   | 2018-11-01 |
|  1 | Out  | 2018-12-01 |
|  2 | In   | 2018-10-01 |
|  2 | Out  | 2018-11-01 |
|  2 | In   | 2018-12-01 |
+----+------+------------+

我真的迷失了查询这个问题。 我从

开始
SELECT #Table.*, MIN(CASE WHEN #Table.[type] = 'In' THEN #Table.Dates ELSE NULL END) As A
    ,MIN(CASE WHEN #Table.[type] = 'Out' THEN #Table.Dates ELSE NULL END) As B
FROM #Table
GROUP BY #Table.id, #Table.[type], #Table.Dates

不知道从那里做什么......

最佳答案

如果我理解正确,聚合和 having 就可以了:

select t.id
from #Table t
group by t.id
having min(case when type = 'In' then dates end) < max(case when type = 'Out' then dates end);

这会选择 ids,其中最早的“in”在最新的“out”之前。

如果需要匹配行,可以使用窗口函数,inexistsjoin:

select t.*
from #table t
where t.id in (select t2.id
               from #Table t2
               group by t2.id
               having min(case when t2.type = 'In' then t2.dates end) < max(case when t2.type = 'Out' then t2.dates end)
              );

关于sql - 如何根据出现的列序列提取行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53856300/

相关文章:

sql - SQL Server 中的相交

sql - oracle 中的合并语句帮助

sql - R-SQL 来自泛型函数 ‘fetch’ 的无效值,类 “try-error”,预期为 “data.frame”

mysql - sql查询执行时间很长

java - Hibernate 相当于 getTimestamp() 和 getInt()

sql - 每个日期的SQL计数

sql-server - 区分大小写的字符串比较

sql-server - Visual Studio团队在线服务-运行sql脚本

mysql - (SQL) 联合与附加数据的组合

mysql - 如何使用sql查询在delphi中搜索ado数据库中的字段?