0

我应该如何构造 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,可以在结果表中看到。即我想查询最近的(列“发生”)不同(列“display_term”)记录。

提前致谢

4

3 回答 3

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'
  )
于 2012-12-31T13:58:28.010 回答
0

你说你想要最近的。目前尚不清楚这到底意味着什么。您上面的示例显示了每个显示项的最大值。如果您想要每个显示项的最大值,您需要使用聚合。这是通过使用 Group By 和 Max 方法来实现的。

SELECT display_term, Max(occurence) as MaxOccurrence
FROM TABLE_NAME
GROUP BY display_term
于 2012-12-31T12:55:29.537 回答
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
于 2012-12-31T14:19:40.967 回答