SQL 查询查找表中所有出现的情况

问题描述 投票:0回答:1

我需要一个可以返回表中特定条件对的所有出现的查询。 例如,我有这张桌子。我需要返回所有“开始到停止”的航段,其中 startPointType 是 L 或 D,而 endPointType 不是 L 或 D。

起点 起始点类型 终点 端点类型
1 xxx L 啊啊 D
2 啊啊 L 哎呀 Z
3 哎呀 Z ttt C
4 ttt C 呜呜 D
5 呜呜 L L
6 L 呵呵 C
7 呵呵 C kk B
8 kk B ppp C
9 ppp C ff L
10 ff L www L

enter image description here

在上面的例子中,它应该返回

开始_腿 起点 结束_腿 终点
2 啊啊 4 呜呜
6 9 ff

我能够找到第一对,但不知道如何获得所有对.. 非常感谢您的帮助。

我尝试过自我加入。

我期待得到所有的对。

sql sql-server database sql-server-2008 join
1个回答
0
投票

考虑到帖子中所需的输出,我认为请求应该是:

  1. 起始记录的 StartPointType 在 ('L','D') 中,EndPointType 不在 ('L','D') 中
  2. 停止记录的 StartPointType 不在 ('L','D') 中且 EndPointType 在 ('L','D') 中

如果我没有理解错的话,以下查询给出了所需的结果:

select top 1 with ties StartLeg = a.leg
  ,a.StartPoint
  ,EndLeg = b.leg
  ,b.EndPoint
from MyTable a
inner join MyTable b
on a.leg<b.leg
 and b.StartPointType not in ('L','D')
 and b.EndPointType in ('L','D')
where a.StartPointType in ('L','D')
 and a.EndPointType not in ('L','D')
order by row_number() over (partition by a.leg order by b.leg)

其中 MyTable 是一张类似于帖子中的表格。我将它与自身连接起来,其中别名是“a”,我正在寻找开始记录,“b”在哪里,我正在寻找停止记录:这就是我写a.leg的原因

我之所以写 select top 1 with ties 并在最后写 order by 是因为我希望每个分区键只有一条记录,在我们的例子中是一条腿。如果有许多记录具有相同的 a.leg,我只想保留具有较小 b.leg 的记录(这就是为什么在 row_number() 中我按 b.leg 进行排序)。

此解决方案无法在 sql server 2008 中工作,在这种情况下我将使用 CTE(或临时表,根据您的喜好):

with tab as (select StartLeg = a.leg
  ,EndLeg = min(b.leg)
from MyTable a
inner join MyTable b
on a.leg<b.leg
 and b.StartPointType not in ('L','D')
 and b.EndPointType in ('L','D')
where a.StartPointType in ('L','D')
 and a.EndPointType not in ('L','D')
group by a.leg)

select t.StartLeg
  ,a.StartPoint
  ,t.EndLeg
  ,b.EndPoint
from tab t
inner join MyTable a
on t.Startleg=a.leg
inner join MyTable b
on t.Endleg=b.leg
© www.soinside.com 2019 - 2024. All rights reserved.