#1111 - Invalid use of group function error in sql - sql

Does anyone know a solution for this error:
#1111 - Invalid use of group function
This is my SQL:
SELECT leerlingen.leerlingnummer, voornaam, tussenvoegsel, achternaam, klas, leerlingen.bestemming
FROM betalingen, leerlingen, bestemmingen
WHERE leerlingen.leerlingnummer = betalingen.leerlingnummer AND SUM( betalingen.bedrag ) > bestemmingen.bedrag
GROUP BY leerlingen.leerlingnummer

You can't reference the results of an aggregate function (SUM) in predicated query (WHERE), you will have to specify the aggregate in the select, then use a "Having" clause to filter that set.

Related

How not to aggregate on numeric fields

I have this code with which I am trying not to aggregate on two columns HistoryQuantity and TOTFCST. I keep getting this error
Column 'SCPOMGR.HISTWIDE_CHAIN.HistoryQuantity' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
I don't think I should group by numeric columns.
Is there any way around this?
-- WAPE (chain)
SET ARITHABORT OFF
SET ANSI_WARNINGS OFF
SELECT
b.[LOC], b.[DMDUNIT],
ABS(b.HistoryQuantity - a.TOTFCST) AS 'Abs Error',
SUM(b.HistoryQuantity) AS 'Sum of Actuals',
SUM(ABS((b.HistoryQuantity - a.TOTFCST))) AS 'Sum of Abs Error',
SUM(ABS((b.HistoryQuantity - a.TOTFCST))) / SUM(b.HistoryQuantity) AS 'WAPE'
FROM
SCPOMGR.FCSTPERFSTATIC a
JOIN
SCPOMGR.HISTWIDE_CHAIN b ON a.[STARTDATE] = b.[DMDPostDate]
AND a.[DMDUNIT] = b.[DMDUNIT]
AND a.[LOC] = b.[LOC]
GROUP BY
b.[LOC], b.[DMDUNIT], b.[DMDPostDate]
ORDER BY
b.[LOC]
ABS() is not an aggregate function and cannot be used without, for example, passing aggregate values to it
use any like this
ABS(Sum(b.HistoryQuantity) - Sum(a.TOTFCST))

Error : Cannot perform an aggregate function on an expression containing an aggregate or a subquery

I tried to write this in one of my SQL stored procedure. Just a simple logic to just check if the #kPortalOrigin exists in the table [cli].[tbl_S_PortalOrigin]:
IF (COUNT ((SELECT kPortalOrigin
FROM [cli].[tbl_S_PortalOrigin]
WHERE kPortalOrigin = #kPortalOrigin)) = 0)
RAISERROR('Portal Origin is invalid!', 16, 1)
However, I get this error:
Cannot perform an aggregate function on an expression containing an aggregate or a subquery
Any help? Thanks. And I would not mind an explanation why this error occurs.
if EXISTs ((select kPortalOrigin from [cli].[tbl_S_PortalOrigin] where kPortalOrigin = #kPortalOrigin)) RAISERROR('Portal Origin is invalid!',16,1)
this will works.

Using sum function in sql view in oracle database

I am trying to create a view using some o group function like sum , avg etc. it is giving error.
create view sample_view as
select A,B,C,D,E,
(a + b+c+d+e)/5 as Mean_value,
GREATEST(a,b,c,d,e)-LEAST(a,b,c,d,e) as range_value,
avg(mean_value)
from samples;
I am getting below error.
Error starting at line : 37 in command -
create view sample_view as select A,B,C,D,E, (a + b+c+d+e)/5 as Mean_value, GREATEST(a,b,c,d,e)-LEAST(a,b,c,d,e) as range_value, avg(mean_value) from samples
Error report -
ORA-00937: not a single-group group function
00937. 00000 - "not a single-group group function"
*Cause:
*Action:
Is there anyway to create view in oracle database using group function. I also tried sum() and count(). all those also giving error.
Root Cause for your problem is:
You tried to execute a SELECT statement that included a GROUP BY function (ie: AVG Function,MIN Function, MAX Function, SUM Function, COUNT Function), but was missing the GROUP BY clause.Try to add Group BY clause and run the query.
You can try the below - since avg() is an aggregate function you can not add this with other columns without adding group by the clause -
create view sample_view as
select A,B,C,D,E, (a + b+c+d+e)/5 as Mean_value,
GREATEST(a,b,c,d,e)-LEAST(a,b,c,d,e) as range_value,
avg((a + b+c+d+e)/5) over()
from samples;

Syntax error in query expression using sub query

SELECT
(
SELECT Sum(tbl_allTransactions.transAmount) AS SumOftransAmount
FROM tbl_allTransactions
WHERE (((tbl_allTransactions.[transType])='Expense')) OR (((tbl_allTransactions.[transType])='Budget') AND ((tbl_allTransactions.[transMonth])=[#transMonth]))
GROUP BY tbl_allTransactions.transMonth
,
SELECT Sum(tbl_allTransactions.transAmount) AS SumOftransAmount
FROM tbl_allTransactions
WHERE (((tbl_allTransactions.[transType])='Expense')) OR (((tbl_allTransactions.[transType])='Budget') AND ((tbl_allTransactions.[transMonth])=[#transMonth]))
GROUP BY tbl_allTransactions.transMonth
)
FROM tbl_allTransactions WHERE (((tbl_allTransactions.[userID])=[#userID]))
I am getting following error:-
System.Data.OleDb.OleDbException (0x80040E14) Syntax error in query
expression '(SELECT Sum(tbl_allTransactions.transAmount) AS
SumOftransAmount FROM tbl_allTransactions WHERE
(((tbl_allTransactions.[transType])='Expense')) OR
(((tbl_allTransactions.[transType])='Budget') AND
((tbl_allTransactions.[transMonth])=[#transMonth])) GROUP '. at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResulthr) at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS
dbParams, Object& executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteCommandText(Obje
The original code was missing a closing parenthesis on the first subquery. The code was also simplified by consolidating the transType conditional from 2 statements to 1. Extra brackets were removed to enhance readability. Also column aliases were added to output of each subquery. Since both queries render the same data, the second column was called "SumOftransAmount2"
SELECT
(SELECT Sum(tbl_allTransactions.transAmount)
FROM tbl_allTransactions
WHERE tbl_allTransactions.transType in ('Expense', 'Budget') AND tbl_allTransactions.transMonth = #transMonth
GROUP BY tbl_allTransactions.transMonth) as SumOftransAmount
,
(SELECT Sum(tbl_allTransactions.transAmount)
FROM tbl_allTransactions
WHERE tbl_allTransactions.transType in ('Expense', 'Budget') AND tbl_allTransactions.transMonth = #transMonth
GROUP BY tbl_allTransactions.transMonth) as SumOftransAmount2
FROM tbl_allTransactions
WHERE tbl_allTransactions.userID=#userID

PostgreSQL asking for 'group by' clause in where, when sending parameters

I have a simple query in PostgreSQL which is ok when I run it without any query parameters :
select date_trunc('week', action_time),count(*) from event
group by date_trunc('week', action_time);
But if I try to send the 'week' as a parameter like this (in Java):
PreparedStatement statement = connection.prepareStatement
("select date_trunc(?, action_time),count(*) from event"
+ " group by date_trunc(?, action_time)");
statement.setString(1,"week");
statement.setString(2,"week");
statement.execute();
it'll throw the following error:
ERROR: column "event.action_time" must appear in the GROUP BY clause or
be used in an aggregate function
is this normal behavior ?
When the query is prepared there's no guarantee that you will bind the same value ('week') for both placeholders. If you don't, the query would be illegal, and that's why postgres doesn't allow preparing it.
One way around this could be to change your query so you only bind 'week' once, and use it from inside a subquery:
PreparedStatement statement = connection.prepareStatement
("select dt, count(*) from (select date_trunc(?, action_time) as dt "
+ "from event) s group by dt");
statement.setString(1,"week");
statement.execute();
I think this should work, but Postgres can be a bit finicky. For instance, the following does not work:
select date_trunc(val, now())
from (select 'week' as val) t
But this does:
select date_trunc(val, now())
from (select cast('week' as text) as val) t
You might check if this version works:
select date_trunc(datepart, action_time), count(*)
from event cross join
(select cast(? as text) as datepart) vars
group by date_trunc(datepart, action_time);
And then supply only one parameter.
Like Mureinik mentioned its because postgres cant prove the statement arguments are the same.
I was able to use a column alias to provide the argument once.
eg
select date_trunc(?, action_time), count(*) from event
group by date_trunc(?, action_time);
becomes
select date_trunc(?, action_time) as action_t, count(*) from event
group by action_t;