我在SQL Server中有一个视图,它显示的结果与简单查询的结果不同。
我尝试创建新视图,尝试使用sp_RefreshView,我从“创建视图”更改了一些代码,我不知道它可以是什么。 正确的结果来自查询,而不是来自视图。
为什么不同?
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/****** Object: View [QEHS].[V_FactMonitorings25261gui] Script Date: 11/07/2019 16:24:53 ******/
CREATE view
[QEHS].[V_FactMonitorings25261gui]
as
with
Plants as
(
select distinct
[plant-id]
from
[QEHS].[Fact-Monitorings-H&S]
) ,
MIDs as
(
select mid
from
(
values
( 'MON.02.25 Total number of LTA free days (calendar days)')
,( 'MON.02.26 Total number of TRI free days (calendar days)')
) as x(mid)
),
PlantList
AS
(
select
a.date,
b.[plant-id],
c.mid
from
QEHS.Calendar_Gen A
cross join
plants b
cross join mids c
where
year(a.date) >= 2011
),
help1 as
(
SELECT
p.date,
p.[plant-id],
p.mid,
t.value,
(
case
when (year(p.date) = year(getdate()) and month(p.date) = month(getdate())) then
day(getdate())
else
iif(t.value is not null, 0, day(eomonth(p.date)))
end
) Days,
cast(isnull(cast(t.value as bit),0) as integer) reset
FROM
PLANTLIST p
left join
[QEHS].[Fact-Monitorings-H&S] T
on
(
p.date = t.date and
p.[plant-id] = t.[plant-id] and
p.mid = t.[monitoring-id]
)
),
help2 as
(
select
date,
[plant-id],
mid,
value,
days,
reset,
formatmessage('%s%s%d', [plant-id], mid,sum(reset) over
(
partition by [plant-id], mid
order by date, [plant-id], mid
)
) grp
from
help1
where
year(date) >= (select year(min(date)) from [QEHS].[Fact-Monitorings-H&S])
),
help3 as
(
select
date,
[plant-id],
mid,
value,
days,
first_value(value) over (partition by grp order by date, [plant-id], mid) fullvalue
from
help2
)
--
select
date,
[plant-id],
mid,
isnull(a.Value,
fullvalue +sum(days) over
(
partition by [plant-id], mid, fullvalue
order by mid, date, [plant-id]
rows between unbounded preceding and current row
)
) total
from
help3 a
GO
它在视图中显示了不同的结果,如果我从视图中获取代码并简单地进行查询,我将获得正确的结果。