在sql中使用update语句的子查询

时间:2015-06-10 06:03:49

标签: sql sql-server

我有以下查询:

int

我需要根据结果更新表'tmp_table'。我尝试了以下方法,但它不起作用:

SELECT
    CONVERT(datetime, CONVERT(varchar, new_time, 101)) As day,
    datepart(hh,new_time) As hour,count(*) As Total
FROM 
   log_table
WHERE 
   new_time > GETDATE() - 180
GROUP BY 
   CONVERT(datetime, CONVERT(varchar, new_time, 101)),datepart(dd,new_time), datepart(hh,new_time)
ORDER BY 
   CONVERT(datetime, CONVERT(varchar, new_time, 101)), datepart(hh,new_time));

我需要从子查询中获取值“Total”,“day”和“hour”。

1 个答案:

答案 0 :(得分:1)

如果您只想更新,那么您不需要订购,因此您可以使用CTE和连接:

 With CTE AS 
    (
        SELECT CONVERT(DATETIME, CONVERT(VARCHAR, new_time, 101)) As day,
               DATEPART(hh,new_time) As hour,
               COUNT(*) As Total
        FROM log_table 
        WHERE new_time > GETDATE() - 180
        GROUP BY  CONVERT(DATETIME, CONVERT(VARCHAR, new_time, 101)),
                  DATEPART(dd,new_time),
                  DATEPART(hh,new_time)
    )
    UPDATE tmp_table
    SET Count= CTE.Total
    FROM tmp_table INNER JOIN CTE
         ON temp_table.date=cte.day AND temp_table.hour=cte.hour