从SQL Server中的另一个表转换数据后更新表?

时间:2014-02-05 07:17:11

标签: sql sql-server

我有两个表,我想用两个表中日期相等的另一个表的列更新一个表的列。这里的问题是两个表中的日期不同。

SELECT UploadedDateTime = LEFT(CAST(UploadedDateTime AS DATETIME), 11),
        COUNT(DISTINCT ClientID) AS 'DocsCount' 
FROM ClientUploadedTaxDocuments
WHERE CONVERT(DATETIME, CONVERT(NVARCHAR(10), UploadedDateTime, 101)) > '1/1/2014' 
GROUP BY LEFT(CAST(UploadedDateTime AS DATETIME), 11)
ORDER BY LEFT(CAST(UploadedDateTime AS DATETIME), 11) 

以上查询的输出是,

1 .. enter image description here

从FilesReceivedReport

中选择*

2 .. enter image description here

这里我想用DocsCount(第1表的列)更新Y2014(第2表的列),其中日期相等。

由于

1 个答案:

答案 0 :(得分:0)

首先,给第一个选定的列一些好名字。添加“AS日期”,它变为

SELECT UploadedDateTime = LEFT(CAST(UploadedDateTime AS DATETIME), 11) AS 'Date',
    COUNT(DISTINCT ClientID) AS 'DocsCount' 
FROM ClientUploadedTaxDocuments
WHERE CONVERT(DATETIME, CONVERT(NVARCHAR(10), UploadedDateTime, 101)) > '1/1/2014' 
GROUP BY LEFT(CAST(UploadedDateTime AS DATETIME), 11)
ORDER BY LEFT(CAST(UploadedDateTime AS DATETIME), 11) 

然后,尝试这样的事情:

UPDATE f set Y2014 = s.DocsCount FROM FilesReceivedReport AS f
INNER JOIN (your_complicated_select) AS s
ON f.D == s.Date