1

假设我在 SQL Server 中有下表:

Date         ColA         ColB
1/1/2013     Val1A        Val1B
1/1/2013     Val2A        NULL
1/1/2013     Val3A        Val3B
1/2/2013     Val1A        NULL
1/2/2013     Val2A        Val4B

而且,我希望看到每天的变化ColB- 在这种情况下可能如下所示:

Date         ColA         ColB_Today       ColB_Prev_Day
1/2/2013     Val1A        NULL             Val1B
1/2/2013     Val2A        Val4B            NULL
1/2/2013     Val3A        NULL             Val3B

因此,为此,我创建了一个相当复杂的查询(将表连接到自身),它有一个输入变量和一个计算变量,如下所示:

DECLARE @Date Date = '1/2/2013', @PrevDay Date;
SET @PrevDay = (Select TOP 1 Date from MyTable where Date < @Date order BY Date desc);

SELECT
  @Date as 'Date',
  T1.ColA,
  T1.ColB as ColB_Today,
  T2.ColB as ColB_Prev_Day
FROM
  (SELECT * FROM MyTable where Date = @Date) T1,
 FULL OUTER JOIN
  (SELECT * FROM MyTable where Date = @PrevDay) T2
 ON
  T1.ColA = T2.ColA

这就是我要找的。

现在,我希望能够将其转换为视图(不传递任何参数)而不是这个参数化查询。

我希望我想做的事情是有意义的......换句话说,视图将具有列Date,ColAColB_Today&ColB_Prev_Day它只是从表中提取数据以创建相同的结果而无需参数化日期(简单地说,基于表中可用的日期) - 我最大的挑战似乎是Val3A上面的行,它只对两个日期之一有一个值,而不是两个......

有什么想法吗???

谢谢!!

4

1 回答 1

2

你可以使用这样丑陋的东西:

with cte_dates as (
    select distinct [Date] from MyTable
), cte_vals as (
    select distinct ColA from MyTable
)
select
    d.[Date],
    v.ColA,
    T1.ColB as ColB_Today,
    T2.ColB as ColB_Prev_Day
from cte_dates as d
    cross join cte_vals as v
    left outer join MyTable as T1 on T1.ColA = v.ColA and T1.[Date] = d.[Date]
    outer apply (
        select top 1 TT.ColB
        from MyTable as TT
        where TT.ColA = v.ColA and TT.[Date] < d.[Date]
        order by TT.[Date] desc
    ) as T2

=> sql 小提琴演示

在我了解更多关于您的数据之前,很难做得更好。您的表格中的日期之间有间隔吗?

于 2013-09-03T19:04:05.860 回答