SQL INSERT INTO SELECT Statement Invalid use of group function - mysql

I've the following query:
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;
When I run the query I get the next mistake:
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
why ocurre this?
how to fix it?

You are mixing a values statement with a select statement in insert. You only need select. This is my best guess on what you want:
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;
However, you should also list the column names for StatisticalConsultationAgreement in the insert statement.

You are not grouping EndDateTimeProcessing and when you try to do the Insert it can't figure out which EndDateTimeProcessing value, from the grouped rows, it should take.
The solution is either you add it on your group clause:
GROUP BY entityType,entitycode,queryType, queryClass, EndDateTimeProcessing;
Or you use a function group as MAX(), MIN(), etc.
Best Regards
EDIT
As said by Gordon Linoff, you are also mixing the query with the INSERT, everything should be gotten by the query.
The right syntax should be:
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;
The fields MONTH(EndDateTimeProcessing),YEAR(EndDateTimeProcessing), for the query were removed because i didn't know where thouse should be

Related

Trying to combine INSERT and SELECT queries in MYSQL DB

I have been trying to combine SELECT and INSERT queries, but with no luck. The below query works well..
INSERT INTO counts (count)
SELECT COUNT(*) FROM `twitter` WHERE created_local > NOW() - INTERVAL 10 MINUTE AND text LIKE '%USDJPY%'
My DB columns that I do INSERT query are "pair" and "count".
In above query the count is inserted into the counts table > count column but I am also trying to insert in the above case "USDJPY", tried different combinations but all end up with sql error.
I would appriciate a feedback...
Just select a constant for the literal value you want to insert. And also, please specify all column names which are being targeted by your insert.
INSERT INTO counts (pair, count)
SELECT 'USDJPY', COUNT(*)
FROM twitter
WHERE created_local > NOW() - INTERVAL 10 MINUTE AND text LIKE '%USDJPY%';

MySQL return summed values and a virtual column as (count - sum)

I have a table as follows:
log (log_id, log_success (bool), log_created)
I would like to SELECT and return 3 columns date success and no_success, where the former does not exist in table and finally aggregate them by day.
I have created this query:
SELECT
log_created as 'date'
COUNT(*) AS 'count',
SUM(log_success) AS 'success'
SUM('count' - 'success') AS 'no_success'
FROM send_log
GROUP BY DATE_FORMAT(log_created, '%Y-%m-%d');
Would I be able to achieve it with this query? Is my syntax correct?
Thanks.
You can't reuse an alias defined in the select within the same select clause. The reason for this is that it might not even have been defined when you go to access it. But, you easily enough can repeat the logic:
SELECT
log_created AS date,
SUM(log_success) AS success,
COUNT(*) - SUM(log_success) AS no_success,
FROM send_log
GROUP BY
log_created;
I don't know why you are calling DATE_FORMAT in the group by clause of your query. DATE_FORMAT is usually a presentation layer function, which you call because you want to view a date formatted a certain way. Since it appears that log_created is already a date, there is no need to call DATE_FORMAT on it when aggregating. You also should not even need in the select clause, because the default format for a MySQL date is already Y-m-d.
You must select DATE_FORMAT(log_created, '%Y-%m-%d') if you want to group by this.
Also you can get the no_success counter with SUM(abs(log_success - 1))
SELECT
DATE_FORMAT(log_created, '%Y-%m-%d') date,
SUM(log_success) log_success,
SUM(abs(log_success - 1)) no_success
FROM send_log
GROUP BY date;
See the demo

SQL function to separate a record into two records.

I have created date and resolved date in Table1. Both fields are included in one record.
ID created_date resolved_at
'1xxxx' '18-04-2018' '20-04-2018'
Is it possible that i may use custom SQL function to separate them into 2 records.
I want somehow output like this.
ID date Operation
1xxx. 18-04-2018. Created
1xxx. 20-04-2018. Resolved
SELECT ID,created_date DATE,CASE WHEN CREATED_DATE IS NOT NULL THEN 'Created' end OPERATION FROM TABLE1
UNION
SELECT ID,resolved_at DATE,CASE WHEN resolved_at IS NOT NULL THEN 'Resolved' end OPERATION FROM TABLE1
You simply need to use CASE WHEN and according to which ever column is not null we will make that name as OPERATION.
You can check SQL fiddle here
Try above query.
It will help you.
The simpler solution is:
select id, created_date, 'created' as operation from t
union all
select id, resolved_at, 'resolved' as operation from t;

Mysql: Using str_to_date on a select query returns nothing

I've following Mysql query:
select str_to_date((select distinct cast(substr(tb2.sub1,1,4) AS CHAR) as year from (
SELECT SUBSTRING_INDEX(file_name,'_',-1) as sub1 from table2) as tb2) , '%Y')
And it is correct because mysqlworkbench returns green flag but no output.
Could you help me?
The expression
select str_to_date('2007', '%Y')
returns 2007-00-00. Some MySQL servers are set to disallow invalid dates. Try using
select makedate('2007', 1)
instead. That will give you the valid date of 2007-01-01.
I'm leaving it to you to edit your query to make the change.

MySQL INSERT... SELECT column count and virtual/aliased columns

I'm trying to insert using a select statement. However, I need to order the sub-select results using a ranking equation. If I create an alias, it throws off the column count. Can I somehow order my results using an equation?
INSERT INTO draft
( fk_contrib_id , end_time )
SELECT pk_contrib_id, UNIX_TIMESTAMP(), (X+Y+Z) AS ranking
FROM contrib
ORDER BY ranking DESC
LIMIT 1
I need the 'ranking' column for sorting, but if I do, the column count is off for the insert. Do I have to use two queries for this?
You could simply change your query to directly use the expression in the ORDER BY clause, like so:
INSERT INTO draft
( fk_contrib_id , end_time )
SELECT pk_contrib_id, UNIX_TIMESTAMP()
FROM contrib
ORDER BY (X+Y+Z) DESC
LIMIT 1
Remove the expression from the SELECT list. And use the expression in the ORDER BY clause.
ORDER BY X+Y+Z
It's perfectly valid to ORDER BY expressions that are not in the SELECT list.