0

我一直在寻找以下问题的解决方案,遗憾的是无济于事。这适用于 Microsoft SQL Server 上的 Microsoft SQL Server Management Studio。

数据库看起来或多或少像这样:

ID    LegID   TripID     
1     0       0  
1     0       1  
1     1       0  
2     0       0  
2     1       0 
2     2       0 
2     2       1  
3     0       0 
3     0       1 
3     0       2

我正在寻找一个结果,其中所有记录都将选择为 legID 不超过 1 且 TripID 不超过 1 的 ID。那么结果应该是:

ID    LegID   TripID     
1     0       0  
1     0       1  
1     1       0

你能帮我解决这个问题吗?

4

2 回答 2

0

一种方法使用not exists

select t.*
from t
where not exists (select 1
                  from t t2
                  where t2.id = t.id and
                        (t2.LegId > 1 or t2.TripId > 1)
                 );

出于性能考虑,您需要在(id, legid, tripid).

您还可以使用窗口函数:

select t.*
from (select t.*,
             max(legid) over (partition by id) as max_legid,
             max(tripid) over (partition by id) as max_tripid
      from t
     ) t
where max_legid <= 1 and max_tripid <= 1;
于 2019-09-18T11:31:49.267 回答
0

id利用基于条件聚合的过滤,使用派生表(子查询)来获取符合您要求的所有值。然后,连接回主表以获取这些id值的所有行。

SELECT 
  t1.* 
FROM 
  your_table_name t1 
JOIN (SELECT ID
      FROM your_table_name 
      GROUP BY ID 
      HAVING MAX(LegID) <= 1 
         AND MAX(TripID) <= 1) t2 ON t2.ID = t1.ID
于 2019-09-18T11:33:55.730 回答