由LAG函数定义的SQL查找键

时间:2015-01-22 14:03:39

标签: join sql-server-2008-r2 lag

我想基于LAG函数在一个键上连接两个表。我的查询不起作用。我收到一个错误:

  

消息4108,级别15,状态1,行13窗口函数只能出现在SELECT或ORDER BY子句中。

我将不胜感激任何有关如何解决这个问题的建议。

**Table A**
Key
1
2
3
and so on...

**Table B**
MaxKey | Something
3 | A
5 | B
8 | C

**Expected Results**
Key|Something
1 A
2 A
3 A
4 B
5 B
6 C


SELECT
   tabA.Key
  ,tabB.[Something]
  ,LAG (tabB.MaxKey,1,1) OVER (ORDER BY tabB.MaxKey) AS MinKey
  ,tabB.[MaxKey] 
FROM TableA as tabA 
LEFT JOIN TableB as tabB 
ON tabA.Key > tabB.MinKey AND tabA.Key <= tabB.MaxKey

1 个答案:

答案 0 :(得分:1)

我认为你可以使用这样的外部应用来解决这个问题:

select * from TableA a
outer apply (
  select top 1 something 
  from TableB b 
  where b.maxkey >= a.[key]
) oa

Sample SQL Fiddle

另一种选择是修改您的查询以在派生表中执行延迟,我相信这也可能有效:

SELECT
   tabA.[Key]
  ,tabB.[Something]
  ,MinKey
  ,tabB.[MaxKey] 
FROM TableA as tabA 
LEFT JOIN (
    SELECT 
       [Something]
       ,LAG (MaxKey,1,1) OVER (ORDER BY MaxKey) AS MinKey
       ,[MaxKey] 
    FROM TableB) tabB
ON tabA.[key] >= tabB.MinKey AND tabA.[key] <= tabB.MaxKey
ORDER BY tabA.[key]