小编典典

将数据从表插入

sql

我有一张表格,列出了来自特定网站的评论数量,如下所示:

Date                        Site         Comments         Total
---------------------------------------------------------------
2010-04-01 00:00:00.000      1              5               5
2010-04-01 00:00:00.000      2              8               13
2010-04-01 00:00:00.000      4              2               7
2010-04-01 00:00:00.000      7              13              13
2010-04-01 00:00:00.000      9              1               2

我还有另一个表,列出了所有站点,例如从1到10

Site
-----
1
2
...
9
10

使用以下代码,我可以找出上个月缺少哪些站点条目:

SELECT s.site
from tbl_Sites s
EXCEPT
SELECT c.site
from tbl_Comments c
WHERE c.[Date] = DATEADD(mm, DATEDIFF(mm, 0, GetDate()) -1,0)

生产:

site
-----
3
5
6
8
10

我希望能够使用一些默认值(即“ 0”)将查询中列出的缺失网站插入到注释表中

Date                        Site         Comments         Total
---------------------------------------------------------------
2010-04-01 00:00:00.000      3              0               0
2010-04-01 00:00:00.000      5              0               0
2010-04-01 00:00:00.000      6              0               0
2010-04-01 00:00:00.000      8              0               0
2010-04-01 00:00:00.000      10             0               0

问题是,我如何更新/插入表/值?


阅读 163

收藏
2021-04-14

共1个答案

小编典典

INSERT INTO CommentTable (Date, Site, Comments, Total)
SELECT ‘2010-04-01 00:00:00.000’, Site, 0, 0
FROM SiteTable
WHERE Site NOT IN
(SELECT DISTINCT Site FROM CommmentTable
WHERE [Date] = DATEADD(mm, DATEDIFF(mm, 0, GetDate()) -1,0))

2021-04-14