1

我有点卡住了。我有一个包含以下列的数据库表:

Table Name: Data
*Value
*DateTime
*WeekNumber
*ItemId
*Name

我创建了以下脚本,我想将结果放入上表中。

SELECT D.*, M.Name
FROM
(SELECT SUM (Data) AS [Value],
(SELECT CONVERT(Date,DATEADD(week,-1,GETDATE()))) [DateTimeValue], DatePart (Week,TimestampUTC) [WeekNumber], MT.MeterId [MeterID]

FROM DataLog.dl
JOIN MeterTags mt ON dl.MeterTagId = mt.MeterTagId
GROUP BY DatePart (Week,TimestampUTC, dl.MeterTagId, MeterId)
AS D
INNER JOIN Meters m
ON D.MeterId = M.MeterId
ORDER BY MeterId DESC

我希望将上述查询的结果放入 db 表中的相应列中,同时为 MeterID 创建一个新列:

Value = Value
DateTime = DateTimeValue
WeekNumber = WeekNumber
MeterID = ***Need to create a new column*****
Name = Name

我希望这是有道理的,因为我对 SQL 非常缺乏经验,并且很难将最后的部分放在一起。您可以提供的任何帮助将不胜感激。

谢谢。

4

2 回答 2

0

您可以使用标准 SQLINSERT语法 INSERT INTO table2 SELECT * FROM table1;

我不明白你是什么意思

MeterID =需要新建一列**

有关更多信息,请查看 http://www.w3schools.com/sql/sql_insert_into_select.asphttp://msdn.microsoft.com/en-us/library/ms188263(v=sql.105).aspx

于 2013-07-03T16:44:31.443 回答
0

修改您的表并为 MeterId 添加新列。

Insert into [Data]
SELECT D.[Value], D.DateTimeValue,D.WeekNumber,MT.MeterId,M.Name
FROM
(SELECT SUM (Data) AS [Value],
(SELECT CONVERT(Date,DATEADD(week,-1,GETDATE()))) [DateTimeValue], DatePart (Week,TimestampUTC) [WeekNumber], MT.MeterId [MeterID]

FROM DataLog.dl
JOIN MeterTags mt ON dl.MeterTagId = mt.MeterTagId
GROUP BY DatePart (Week,TimestampUTC, dl.MeterTagId, MeterId)
AS D
INNER JOIN Meters m
ON D.MeterId = M.MeterId
ORDER BY MeterId DESC
于 2013-07-03T16:52:53.257 回答