我有点卡住了。我有一个包含以下列的数据库表:
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很缺乏经验并且很难将最后的部分组合在一起。您将给予的任何帮助将不胜感激。
感谢。
答案 0 :(得分:0)
您可以使用标准SQL INSERT
语法
INSERT INTO table2
SELECT * FROM table1;
我不明白的是你的意思
MeterID = 需要创建新列 **
了解更多信息 http://www.w3schools.com/sql/sql_insert_into_select.asp和 http://msdn.microsoft.com/en-us/library/ms188263(v=sql.105).aspx
答案 1 :(得分: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