假设我在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
这就是我要找的。 p>
现在,我希望能够将其转换为View(没有传递参数),而不是这个参数化的查询。
我希望我要做的事情有意义......换句话说,视图会有Date
,ColA
,ColB_Today
和& ColB_Prev_Day
它只是从表中提取数据以创建相同的结果,而不必对日期进行参数化(简单地说,基于表中可用的日期) - 我最大的挑战似乎是Val3A
行以上只有两个日期之一的值,而不是两个...
有什么想法???
谢谢!
答案 0 :(得分: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
在我了解您的数据之前,我们很难做得更好。你表中的日期之间是否有差距?