在MSSQL中,要将SQL中每季度每小时值的下一行扩展/填充为每小时值,可以使用窗口函数和日期函数来实现。具体步骤如下:
WITH cte AS (
SELECT
DATEPART(QUARTER, datetime) AS quarter,
DATEPART(HOUR, datetime) AS hour,
value,
ROW_NUMBER() OVER (PARTITION BY DATEPART(QUARTER, datetime), DATEPART(HOUR, datetime) ORDER BY datetime) AS rn
FROM table1
)
SELECT
quarter,
hour,
value
FROM cte
WHERE rn = 1
上述查询会生成一个包含每季度每小时的第一条记录的临时表或子查询。
WITH cte AS (
SELECT
DATEPART(QUARTER, datetime) AS quarter,
DATEPART(HOUR, datetime) AS hour,
value,
LAG(value) OVER (PARTITION BY DATEPART(QUARTER, datetime), DATEPART(HOUR, datetime) ORDER BY datetime) AS prev_value,
DATEDIFF(HOUR, LAG(datetime) OVER (PARTITION BY DATEPART(QUARTER, datetime), DATEPART(HOUR, datetime) ORDER BY datetime), datetime) AS hour_diff
FROM table1
)
SELECT
quarter,
hour,
prev_value AS value
FROM cte
WHERE hour_diff = 1
上述查询会生成一个包含每季度每小时值的下一行数据的临时表或子查询。
WITH cte1 AS (
SELECT
DATEPART(QUARTER, datetime) AS quarter,
DATEPART(HOUR, datetime) AS hour,
value,
ROW_NUMBER() OVER (PARTITION BY DATEPART(QUARTER, datetime), DATEPART(HOUR, datetime) ORDER BY datetime) AS rn
FROM table1
),
cte2 AS (
SELECT
DATEPART(QUARTER, datetime) AS quarter,
DATEPART(HOUR, datetime) AS hour,
value,
LAG(value) OVER (PARTITION BY DATEPART(QUARTER, datetime), DATEPART(HOUR, datetime) ORDER BY datetime) AS prev_value,
DATEDIFF(HOUR, LAG(datetime) OVER (PARTITION BY DATEPART(QUARTER, datetime), DATEPART(HOUR, datetime) ORDER BY datetime), datetime) AS hour_diff
FROM table1
)
SELECT
quarter,
hour,
value
FROM cte1
WHERE rn = 1
UNION
SELECT
quarter,
hour,
prev_value AS value
FROM cte2
WHERE hour_diff = 1
通过以上步骤,你可以将SQL中每季度每小时值的下一行扩展/填充为每小时值。这样得到的结果表将包含每个季度每个小时的值。
请注意,这只是一种实现方法,具体的查询语句可能需要根据实际情况进行调整。同时,关于SQL的具体用法和语法请参考相关文档或教程。
补充:若您在使用腾讯云的数据库产品,推荐使用腾讯云的云数据库SQL Server版(TDSQL)作为MSSQL的云解决方案。TDSQL提供了全面的功能,包括高可用、自动备份、弹性扩缩容等特性,适用于各类应用场景。详情请参考腾讯云数据库SQL Server版(TDSQL)产品介绍:TDSQL产品介绍
领取专属 10元无门槛券
手把手带您无忧上云