一些数据。我添加了一行,以说明重复的表面积。
CREATE TABLE Table1
(id int, id_biens char(3), surface int)
;
INSERT INTO Table1 VALUES
(1, '001', 80),
(2, '001', 50),
(3, '001', 30),
(4, '001', 55),
(5, '001', 50);
这将适用于对。很难将其推广到 SQL 中任意数量的行。这本质上是一个组合问题。您可能需要检查每个可能的行组合,因此在最坏的情况下,您需要生成和评估行集 {1, 2, 3, 4, 12, 13, ... 123, 124... 1234}(例如,在这里使用身份证号)。
对于 1000 行,一次取 4 行可以得到大约 410 亿个组合。统计软件可能是解决此类问题的最佳选择。
我认为,总的来说,以下查询是一种更好的方法。(但请记住我所说的关于统计软件的内容。)它显着改变了你的输出,但我认为这种改变是更好的。哪些行构成总表面要清楚得多。
select distinct b1,
id_1, id_2,
s1, s2,
(s1 + s2) total_surface
from
(select t1.id id_1, t1.id_biens b1, t1.surface s1,
t2.id id_2, t2.id_biens b2, t2.surface s2
from Table1 t1
inner join Table1 t2
on t1.id_biens = t2.id_biens
and t1.id <> t2.id
where t1.id < t2.id
) required_alias
where s1 + s2 between 100 and 105
order by b1, id_1, id_2;
b1 id_1 id_2 s1 s2 total_surface
--
001 2 4 50 55 105
001 2 5 50 50 100
001 4 5 55 50 105
三个值的组合。您需要进行的更改在评论中。
select distinct b1,
id_1, id_2, id_3, -- Add an id,
s1, s2, s3, -- Add a surface
(s1 + s2 + s3) total_surface -- Add surface to the total.
from
(select t1.id id_1, t1.id_biens b1, t1.surface s1,
t2.id id_2, t2.id_biens b2, t2.surface s2,
t3.id id_3, t3.id_biens b3, t3.surface s3 -- Third of three sets of columns.
from Table1 t1
inner join Table1 t2
on t1.id_biens = t2.id_biens
and t1.id <> t2.id
inner join Table1 t3 -- Additional join.
on t1.id_biens = t3.id_biens
and t1.id <> t3.id
where t1.id < t2.id
and t2.id < t3.id -- Additional restriction
) required_alias
where s1 + s2 + s3 between 100 and 105 -- Correct math here, too.