2013-08-24 80 views
0

的我有以下查詢:SQL INSERT INTO SELECT語句無效使用組功能

INSERT INTO StatisticalConsultationAgreement VALUES (
    queryType, entityCode, entityType, queryClass,queryTables,period, 
    COUNT(queryClass), SUM(numberRecords), SUM(recordsFound), 
    SUM(NorecordsFound), NOW(), 'system'); 
SELECT 
    MONTH(EndDateTimeProcessing),YEAR(EndDateTimeProcessing), 
    entityType, 
    entityCode, 
    queryType, 
    queryClass, 
    EndDateTimeProcessing as period 
FROM agreementFile 
WHERE 
    MONTH(EndDateTimeProcessing)=MONTH(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) 
    AND YEAR(EndDateTimeProcessing)=YEAR(CURDATE()) 
GROUP BY entityType,entitycode,queryType, queryClass; 

當我運行查詢,我得到下一個錯誤:

Error code 1111, SQL state HY000: Invalid use of group function 
Line 1, column 1 

Executed successfully in 0,002 s. 
Line 5, column 2 

爲什麼ocurre呢?

如何解決?

+0

你能解釋一下你用這段代碼做什麼?有兩個語句,一個帶有錯誤的INSERT命令(聚合函數SUM和COUNT不能在此上下文中使用)和另一個SELECT語句。 – krokodilko

回答

0

你是混合values語句在select聲明insert。你只需要select。這是你想要什麼我最好的猜測:

INSERT INTO StatisticalConsultationAgreement 
    SELECT queryType, entityCode, entityType, queryClass,queryTables,period, 
      COUNT(queryClass), SUM(numberRecords), SUM(recordsFound), 
      SUM(NorecordsFound), NOW(), 'system' 
    FROM agreementFile 
    WHERE MONTH(EndDateTimeProcessing)=MONTH(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) AND 
      YEAR(EndDateTimeProcessing)=YEAR(CURDATE()) 
    GROUP BY entityType, entitycode, queryType, queryClass; 

但是,你也應該列出列名在insert聲明StatisticalConsultationAgreement

+0

與列名稱完美的工作!謝謝! –

+0

很高興能幫到你。 –

0

您未分組EndDateTimeProcessing並且當您嘗試執行插入操作時,它無法弄清楚應從哪些EndDateTimeProcessing值中分組的行。 解決方法是,你加它在你的組子句:

GROUP BY entityType,entitycode,queryType, queryClass, EndDateTimeProcessing; 

或者你使用一個功能組MAX(),MIN()等

問候

編輯

正如Gordon Linoff所說,您也正在將查詢與INSERT混合,所有事情都應該通過查詢來獲取。

正確的語法應爲:

INSERT INTO StatisticalConsultationAgreement 
SELECT 
    'queryType', --I don't know what is the query type so i put it on single quote 
    entityCode, 
    entityType, 
    queryClass, 
    queryTables, 
    MAX(EndDateTimeProcessing), --Period put on group function MAX, but it cant be grouped below or put into another group function 
    COUNT(queryClass), -- 
    SUM(numberRecords), -- ASUMING THOSE ARE COLUMNS IN agreementFile 
    SUM(recordsFound), -- 
    SUM(NorecordsFound),-- 
    NOW(), 
    'system' 
FROM agreementFile 
WHERE 
    MONTH(EndDateTimeProcessing)=MONTH(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) 
    AND YEAR(EndDateTimeProcessing)=YEAR(CURDATE()) 
GROUP BY entityType,entitycode,queryType, queryClass; 

的字段MONTH(EndDateTimeProcessing),YEAR(EndDateTimeProcessing),的查詢中刪除,因爲我不知道在哪裏thouse應該