我应该如何构造T-SQL语句以实现以下目的: 从这个
表1:
display_term|occurence
A|1
A|4
B|3
B|9
检索此
表2:
display_term|occurence
A|4
B|3
A和B之间的“最近距离”是1,可以在结果表中看到。 即我想查询最近的(列“出现”)distinct(列“display_term”)记录。
提前致谢
答案 0 :(得分:0)
SELECT display_term, Max(occurence) as MaxOccurrence
FROM TABLE_NAME
GROUP BY display_term
答案 1 :(得分:0)
如果单行结果对您有用,则可以执行此操作:
SELECT a.display_term AS adt,
a.occurence As aoc,
b.display_term AS bdt,
b.occurence AS boc,
ABS(a.occurence - b.occurence) AS distance
FROM my_table a, my_table b
WHERE a.display_term = 'A'
AND b.display_term = 'B'
AND ABS(a.occurence - b.occurence) = (
SELECT MIN(ABS(a.occurence - b.occurence))
FROM my_table a, my_table b
WHERE a.display_term = 'A'
AND b.display_term = 'B'
)
答案 2 :(得分:0)
只需两个术语,您就可以执行以下操作:
declare @T table (display_term char(1) not null,occurence int not null)
insert into @T (display_term,occurence) values
('A',1),
('A',4),
('B',3),
('B',9)
select top 1
*
from
@T t1
cross join
@T t2
where
t1.display_term = 'A' and
t2.display_term = 'B'
order by ABS(t1.occurence - t2.occurence)
产生:
display_term occurence display_term occurence
------------ ----------- ------------ -----------
A 4 B 3
(如果您需要完全符合要求的结果集,则可以搜索基于UNPIVOT
的解决方案。
从你的问题中不清楚这是否需要延伸到更多的术语 - 没有明显的方法来重新解释更多术语的要求,所以我暂时不做了。
UNPIVOT
的解决方案,如果需要确切的结果集。如上设置@T
:
select display_term,occurence from (
select top 1
t1.occurence as A,
t2.occurence as B
from
@T t1
cross join
@T t2
where
t1.display_term = 'A' and
t2.display_term = 'B'
order by ABS(t1.occurence - t2.occurence)
) t unpivot (occurence for display_term in (A,B)) as u
结果:
display_term occurence
------------------------------------ -----------
A 4
B 3