在WHERE中使用INSERT INTO

时间:2016-06-08 09:56:40

标签: sql

我有一张表Id | DocId | Page | WordCount

我想为N页插入字数。那就是如果N = 3,那么我想为第1,2和3页添加所有WordCount,然后将它们插入到新表Id | DocId | WordCount

我正在尝试执行以下操作:

INSERT INTO [NewDocTable] (DocId, WordCount)
    SELECT [W].DocId AS DocId, SUM ([W].WordCount) AS WordCount
    FROM [OldDocTable] AS [W]
    WHERE [W].Page <= @N

有人可以帮忙吗?

我有以下错误:列'OldDocTable.DocId'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

3 个答案:

答案 0 :(得分:3)

尝试添加一个组?在这种情况下,您使用摘要函数SUM()这一事实将要求您告诉数据库您要将它们与DocId

相加。
INSERT INTO [NewDocTable] (DocId, WordCount)
    SELECT [W].DocId AS DocId, SUM ([W].WordCount) AS WordCount
    FROM [OldDocTable] AS [W]
    WHERE [W].Page <= @N
    GROUP BY [W].DocId 

答案 1 :(得分:1)

从您的错误消息中可以清楚地看到问题。使用以下查询:

INSERT INTO [NewDocTable] (DocId, WordCount)
    SELECT [W].DocId AS DocId, SUM ([W].WordCount) AS WordCount
    FROM [OldDocTable] AS [W]
    WHERE [W].Page <= @N
    GROUP BY [W].DocId

检查this.

答案 2 :(得分:1)

尝试按语句建议添加组;

INSERT INTO [NewDocTable] (DocId, WordCount)
SELECT [W].DocId AS DocId, SUM ([W].WordCount) AS WordCount
FROM [OldDocTable] AS [W]
WHERE [W].Page <= @N
GROUP BY [W].DocId

问题不在于INSERT INTO,而在于您的SELECT语句。要检查它是否正在执行您期望的操作,最好先自行运行选择以确保它正常工作。