我需要使用日期列提取与在“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);
这会选择 id
s,其中最早的“in”在最新的“out”之前。
如果需要匹配行,可以使用窗口函数,in
、exists
或 join
:
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/