I am using SQL Server 2012 and I am trying to update a table with its own aggregate data.
I have a query similar to this:
DECLARE @temp TABLE
(
RowNo int IDENTITY(1,1),
Date date,
ONDuration int,
DateWiseONDuration int
)
INSERT INTO
@temp(Date, ONDuration)
VALUES
('2014-05-01', 100);
INSERT INTO
@temp(Date, ONDuration)
VALUES
('2014-05-01', 100);
INSERT INTO
@temp(Date, ONDuration)
VALUES
('2014-05-02', 100);
UPDATE
@temp
SET
DateWiseONDuration = (
SELECT
SUM(ONDuration)
FROM
@temp t2
WHERE
@temp.Date = t2.Date
);
SELECT * FROM @temp;
While executing it in SSMS, it says:-
Must declare the scalar variable "@temp".
If I write Date
instead of @temp.Date
, it sums up all ONDuration
s, hence defeats the purpose of WHERE
clause. How can I achieve this in SQL Server 2012?