2

我需要加入,但我不确定是哪种类型。我有一张这样的桌子:

Date        Amount | FOO
------------------
2012-01-12       x
2012-03-14       y
2012-05-06       z
2012-05-14      aa
2012-09-02      bb

我加入了 DateDim (谷歌在这里:DATE DIM,这是一个日期表(历史和未来)。

我需要一个显示如下数据的查询:

datedim.Date    foo.Amount | FOO x DATEDIM
------------------------------------------
2012-01-12               x
2012-01-13               x
2012-01-14               x
... etc...
2012-03-14               y
2012-03-15               y
2012-03-16               y
2012-03-17               y
... etc...
2012-05-06               z
... etc...

基本上,我需要这些值持续存在(如果它是左连接,它将是 NULL),直到下一个非空值。这也会持续存在......等等......


我目前所拥有的...

SELECT datedim.Date
    ,CASE
        WHEN Amount IS NULL
        THEN (SELECT TOP 1 Amount
        FROM FOO WHERE foo.Date <= datedim.Date
        ORDER BY Date DESC)
        ELSE Amount END AS Amount
FROM DATEDIM datedim
LEFT JOIN FOO foo
ON foo.Date = datedim.Date

我需要从中创建一个视图。我收到一条错误消息,说 ORDER BY 对视图无效,除非由 TOP 指定???我在子查询中有一个 TOP ......

4

2 回答 2

1

我确信使用 CTE 或窗口函数有更有效的方法,但是这些方面的东西应该可以工作:

Select
  d.Date,
  d.FooDate,
  f.Amount
From
  Foo f
    Inner Join (
    Select
      d.[Date],
      Max(f.[Date]) as FooDate
    From
      Foo f
       Inner Join
      DateDim d
        On f.[Date] < d.[Date]
    Group By
      d.[Date]
  ) d 
  On d.[FooDate] = f.[Date]

http://sqlfiddle.com/#!3/3c7d5/10

于 2012-11-19T23:19:12.147 回答
1

在 SQLServer2005+ 中使用递归 CTE

;WITH cte (id, [Date], Amount) AS
 (
  SELECT ROW_NUMBER() OVER (ORDER BY [Date] ASC) AS id,
         [Date], Amount
  FROM dbo.your_table t1
  ), cte2 (id, [Date], [LevelDate], Amount) AS
 (         
  SELECT c1.id, c1.[Date], DATEDIFF(day, c1.[Date], c2.[Date]) AS [LevelDate], c1.Amount
  FROM cte c1 LEFT JOIN cte c2 ON c1.id = c2.id - 1
  ), cte3 (id, [Date], Amount, [Level]) AS
 (
  SELECT  id, [Date], Amount, 1 AS [Level]
  FROM cte2 c
  UNION ALL
  SELECT c.id, DATEADD(day, 1, ct.[Date]) AS [Date], c.Amount, ct.[Level] + 1
  FROM cte2 c JOIN cte3 ct ON c.id = ct.id
  WHERE c.[LevelDate] > ct.[Level]
  )
  SELECT [Date], Amount
  FROM cte3
  ORDER BY Date
  OPTION (maxrecursion 0)

SQLFiddle上的演示

于 2012-11-20T01:03:53.650 回答