sql更新表的列,其值由其他表列上的group by组成

时间:2014-12-16 13:03:05

标签: sql-server

我有2个表子主题和userinteractionlog。子主题有timepent列我想更新timespent列,值来自userinteractionlog 通过SubTopicid使用sum(datediff(mi,starttime,endtime))组来进行分组

这是我尝试但没有工作......

UPDATE subtopics s
SET timespent = 
( 
  SELECT SUM(DATEDIFF(mi,u.starttime,u.endtime))
  FROM Userinteractionlog u
  GROUP BY u.subtopicid HAVING s.idsubTopic=u.subtopicid
)

1 个答案:

答案 0 :(得分:0)

CREATE table Userinteractionlog
(
ID int
, starttime datetime
, endtime datetime
, subtopicid int
)
GO

INSERT INTO Userinteractionlog(ID,  starttime, endtime, subtopicid)
VALUES(1,   '2014-01-01 00:00:00.000',  '2014-03-02 00:00:00.000',  1)
,(2,    '2014-05-04 00:00:00.000',  '2014-06-06 12:00:00.000',  1)
,(3,    '2013-01-01 00:00:00.000',  '2013-01-02 00:00:00.000',  2)

CREATE TABLE subtopics
(
timespent bigint
, idsubTopic int
)
GO

INSERT INTO subtopics (timespent, idsubTopic)
VALUES
(NULL,  1)
,(NULL, 2)
GO

UPDATE subtopics
SET timespent = 
( 
  SELECT SUM(DATEDIFF(mi,u.starttime,u.endtime))
  FROM Userinteractionlog u
  GROUP BY u.subtopicid HAVING idsubTopic=u.subtopicid
)
GO

返回

timespent   idsubTopic
134640       1
1440         2