2015-06-10 265 views
0

我有以下查詢:子查詢與更新語句在SQL

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)); 

我需要更新基於其結果表「tmp_table的」。我嘗試以下,但它不工作:

UPDATE tmp_table 
SET count=Total 
WHERE date=day AND hour=hour 
FROM 
(
    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)) 
) 

我需要從子查詢獲得「總」,「日」和「小時」的值。

+0

MySQL和SQL服務器是不同的RDBMS。你在用哪個? –

+0

我正在使用mssql – chinnusaccount

回答

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