我试图在预定义的时间段内检索每个24小时期间值字段的范围。问题是时间段是第二天早上7点到早上7点之间。 (不是每日图)
例如,我想要第1天的范围,然后第2天的范围,等等。我尝试使用以下查询,但生产字段不断回来使用相同的数据,任何人都可以请一些关于我怎么能做这个工作?
非常感谢你。
select tagname, convert(date,datetime),
(
select (max(Value)-min(Value)) as Range
from Runtime.dbo.AnalogHistory
where (TagName = 'LS_CV004_WX1_PROD_DATA.Actual_Input')
and DateTime BETWEEN dateadd(hh,7,convert(datetime,convert(date,datetime))) AND dateadd(hh,31,convert(datetime,convert(date,datetime)))
) as Production
from runtime.dbo.analoghistory
where (TagName = 'LS_CV004_WX1_PROD_DATA.Actual_Input')
and datetime between '20151101' and '20151201'
group by tagname, convert(date,DateTime)
我希望结果如下
标记名|日期|生产
答案 0 :(得分:0)
下面是一种方法,它使用CTE为指定范围内的每个日期生成一行,然后在日期和7小时偏移量上连接到表。考虑为此类任务创建实用程序日历表。
DECLARE
@StartDate date = '20151101'
, @EndDate date = '20151201';
WITH
t8 AS (SELECT n FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0)) t(n))
, t512 AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) - 1 AS num FROM t8 AS a CROSS JOIN t8 AS b CROSS JOIN t8 AS c)
, dates AS (SELECT DATEADD(day, num, @StartDate) AS Date FROM t512 WHERE num <= DATEDIFF(day, @StartDate, @EndDate))
SELECT TagName, Date, MAX(Value)-MIN(Value) as Production
FROM dates
JOIN dbo.AnalogHistory ON
AnalogHistory.DateTime >= DATEADD(hour, 7, Date)
AND AnalogHistory.DateTime < DATEADD(hour, 31, Date)
GROUP BY TagName, Date
ORDER BY TagName, Date;
答案 1 :(得分:0)
您的子查询与外部查询没有关联,因此它返回相同的值也就不足为奇了。我想你想要这样的东西:
select tagname, convert(date, datetime),
(select (max(ah2.Value) - min(ah2.Value)) as Range
from Runtime.dbo.AnalogHistory ah2
where ah2.TagName = 'LS_CV004_WX1_PROD_DATA.Actual_Input' and
ah2.DateTime BETWEEN dateadd(hour, 7, convert(datetime, convert(date, ah.datetime))) AND
dateadd(hour, 31, convert(datetime, convert(date, ah.datetime)))
) as Production
from runtime.dbo.analoghistory ah
where TagName = 'LS_CV004_WX1_PROD_DATA.Actual_Input' and
datetime between '20151101' and '20151201'
group by tagname, convert(date, DateTime);
请注意在子查询中使用ah2
和ah
。