选择最接近的匹配

时间:2017-07-25 20:38:13

标签: sql postgresql inner-join

我正在尝试合并两个表(pc与mc),但下面的语句可以从mc中产生多个记录。我希望查询只返回mc中的匹配,其中cast(pc.ten as date) - cast(mc.to as date)是正数,但尽可能小。我怎么做?

CREATE TABLE test AS SELECT DISTINCT pc.number, mc.number
FROM pc
INNER JOIN mc
ON pc.member = mc.member AND pc.ned = mc.ned AND cast(pc.ten as date) BETWEEN cast(mc.to as date) + 1 AND cast(mc.to as date) + 11 AND
pc.ned IS NOT NULL AND mc.ned IS NOT NULL;

1 个答案:

答案 0 :(得分:1)

CREATE OR REPLACE VIEW test AS 

  SELECT n1, n2 
  FROM (
    SELECT 
      pc.number as n1, 
      mc.number as n2, 
      ROW_NUMBER() OVER (ORDER BY cast(pc.ten as date) - cast(mc.to as date) ASC) AS Rank
    FROM pc
    INNER JOIN mc ON pc.member = mc.member AND pc.ned = mc.ned 
    WHERE cast(pc.ten as date) - cast(mc.to as date) > 0
  ) 
  WHERE Rank = 1