[英]How do I select records where multiple values of different columns have not been exceeded
I've been looking for a solution for the below question, sadly to no avail. 我一直在寻找以下问题的解决方案,可惜没有结果。 This is for Microsoft SQL Server Management Studio on Microsoft SQL Server.
这适用于Microsoft SQL Server上的Microsoft SQL Server Management Studio。
The database looks more or less like this: 数据库看起来或多或少像这样:
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
I'm looking for a result where all records will selected be for the ID's where the legID does not exceed 1 and the TripID does not exceed 1. The result then should be: 我正在寻找一个结果,其中所有记录都将选择为legID不超过1且TripID不超过1的ID。那么结果应为:
ID LegID TripID
1 0 0
1 0 1
1 1 0
Could you please help me with this? 你能帮我这个忙吗?
One method use not exists
: 一种方法
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)
);
For performance, you want an index on (id, legid, tripid)
. 为了提高性能,您需要在
(id, legid, tripid)
上建立索引。
You could also use window functions: 您还可以使用窗口功能:
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;
Use a Derived table (subquery) to get all the id
values matching your requirements, utilizing conditional aggregation based filtering. 通过基于条件聚合的过滤,使用派生表(子查询)来获取所有符合您要求的
id
值。 And, then join back to the main table to get all the rows for those id
value(s). 并且,然后返回主表以获取那些
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.