Sql 返回具有特定日期的多个值的子查询
我有一张结构如下的桌子Sql 返回具有特定日期的多个值的子查询,sql,sql-server,Sql,Sql Server,我有一张结构如下的桌子 CREATE TABLE #T_TrailingYearHours ( RecordDate [DATE], Level5Location [VARCHAR](255), Hours [Float] ) GO 其中包含每个地点过去两年的数据(从2013-07年到2015-06年) 从每个地点的第一个条目(2013-07)开始,小时数列是之前所有小时数的累计总和,因此,当我进入2015-06条目时,它将是过去两年的总小时数 我想根据上面的表格创建一
CREATE TABLE #T_TrailingYearHours (
RecordDate [DATE],
Level5Location [VARCHAR](255),
Hours [Float]
)
GO
其中包含每个地点过去两年的数据(从2013-07年到2015-06年)
从每个地点的第一个条目(2013-07)开始,小时数列是之前所有小时数的累计总和,因此,当我进入2015-06条目时,它将是过去两年的总小时数
我想根据上面的表格创建一个表格,只查看过去12个月(2014年6月至2015年6月)的情况,并显示每个月过去12个月的累计小时数。因此,对于2014年7月,这将是2013年7月至2014年7月之间的累积小时数
我有以下疑问:
DECLARE @CurrentMonth int
DECLARE @CurrentYear int
SET @CurrentMonth = MONTH(GETDATE())
SET @CurrentYear = YEAR(GETDATE())
INSERT INTO #t_trailing12hours
SELECT T.recorddate,
T.level5location,
T.hours - (SELECT TH.hours
FROM #t_trailingyearhours TH
WHERE TH.level5location = T.level5location
AND ( Year(TH.recorddate) = ( Year(T.recorddate) - 1 )
AND Month(TH.recorddate) = Month(T.recorddate) ))
FROM #t_trailingyearhours T
WHERE ( Year(T.recorddate) >= @CurrentYear - 1
AND Month(T.recorddate) >= @CurrentMonth )
OR ( Year(T.recorddate) = @CurrentYear
AND Month(T.recorddate) < @CurrentMonth )
从2014年7月31日到2014年12月31日,我试图查询的任何内容都会产生与上述相同的错误。出于某种原因,它在子查询中返回多个结果,我不知道为什么。我在查询中做错了什么,还有什么我应该做的不同吗?您需要了解子查询是如何工作的 我认为您需要
内部联接
而不是子查询
INSERT INTO #t_trailing12hours
SELECT T.recorddate,
T.level5location,
T.hours - TH.hours
FROM #t_trailingyearhours T
INNER JOIN #t_trailingyearhours TH
ON TH.level5location = T.level5location
AND ( Year(TH.recorddate) = ( Year(T.recorddate) - 1 )
AND Month(TH.recorddate) = Month(T.recorddate) )
WHERE ( Year(T.recorddate) >= @CurrentYear - 1
AND Month(T.recorddate) >= @CurrentMonth )
OR ( Year(T.recorddate) = @CurrentYear
AND Month(T.recorddate) < @CurrentMonth )
插入到#t#u trailing12小时
选择T.recorddate,
T.5级位置,
T小时-TH小时
从#t#u trailingyear t
内部连接#t#u trailingyearth TH
在第5级位置=第5级位置
和(年份(记录日期)=(年份(记录日期)-1)
月份(第次记录日期)=月份(第次记录日期))
其中(年份(T.recorddate)>=当前年份-1
月份(T.recorddate)>=@CurrentMonth)
或(年份(T.recorddate)=当前年份
月份(T.recorddate)<@CurrentMonth)
添加一个MIN
、MAX
或SUM(TH.hours)
我添加了一个编辑,但我想它被覆盖了。如果我只想得到上一年的小时数,这是有意义的,但我需要得到当前月份/年和上一个月份/年的小时数之差,这就是为什么我最终尝试执行子查询的原因。@b马丁-现在更新检查
INSERT INTO #t_trailing12hours
SELECT T.recorddate,
T.level5location,
T.hours - TH.hours
FROM #t_trailingyearhours T
INNER JOIN #t_trailingyearhours TH
ON TH.level5location = T.level5location
AND ( Year(TH.recorddate) = ( Year(T.recorddate) - 1 )
AND Month(TH.recorddate) = Month(T.recorddate) )
WHERE ( Year(T.recorddate) >= @CurrentYear - 1
AND Month(T.recorddate) >= @CurrentMonth )
OR ( Year(T.recorddate) = @CurrentYear
AND Month(T.recorddate) < @CurrentMonth )