Valid GROUP BY query doesn't work when combined with INSERT INTO on Oracle

ぐ巨炮叔叔 提交于 2019-12-21 03:59:18

问题


I'm trying to write an INSERT INTO that does a some DISTINCT/GROUP BY work. The query runs perfectly fine as a select statement, but will not work if it's wrapped into an INSERT INTO.

INSERT INTO MasterRecords
  (BatchRecordRecordID, SourceID, BatchID)
SELECT RecordID, SourceID, BatchID
FROM (
    SELECT RecordID, BatchID, 101 AS SourceID
    FROM BatchRecords
    WHERE BatchID = 150
    GROUP BY RecordID, BatchID
) BR

This earns me:

SQL Error: ORA-00979: not a GROUP BY expression

But if I remove just the INSERT INTO code, it runs perfectly fine:

SELECT RecordID, SourceID, BatchID
FROM (
    SELECT RecordID, BatchID, 101 AS SourceID
    FROM BatchRecords
    WHERE BatchID = 150
    GROUP BY RecordID, BatchID
) BR

Results:

3   101 150
5   101 150
6   101 150
2   101 150
4   101 150
8   101 150
7   101 150
1   101 150

My assumption is that GROUP BY's are not allowed inside INSERT INTO select statements but I can find almost no documentation confirming this.


回答1:


Am I thinking wrong, but is not the sql below equal what you want to achieve?

INSERT INTO MasterRecords(BatchRecordRecordID, SourceID, BatchID)
SELECT DISTINCT RecordID, 101, 150
FROM BatchRecords
WHERE BatchID = 150
;



回答2:


Wonder if it's an order of execution problem... does it work if you use a CTE? CTE must first materialize thus resolve the group by...

  Insert INTO MasterRecords (BatchRecordRecordID, SourceID, BatchID)
   WITH BR AS (
    SELECT RecordID, 101 AS SourceID, 150 AS BatchID
    FROM BatchRecords
    GROUP BY RecordID, 101,150)
  Select RecordID, SourceID, BatchID FROM BR

or... why the group by and where clause in the first place doesn't seem to be doing anything since recordID isn't an aggregate and isn't part of the group by...

Insert into masterRecords (batchrecordRecordID, SourceID, BatchID) SELECT recordID, 101, 150 from batchRecords




回答3:


The problem is solved by automatically changing the value of a parameter (optimizer_features_enable). This value determines the optimizer version of the base, with 11 should not give that problem.



来源:https://stackoverflow.com/questions/28354248/valid-group-by-query-doesnt-work-when-combined-with-insert-into-on-oracle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!