Issue using HAVING-Clause: Invalid expression in the select list (not contained in either an aggregate function or the GROUP BY clause) [duplicate] - sql

I am using Firebird SQL. The below mentioned query returns 4 rows as shown in the figure.
SELECT a.EPS_ID,b.C_NAME,c.AY_YR_NAME,d.S_NAME,e.E_NAME
FROM
TBLEXAMPLANNER_S_MSB a,
TBLCLASS_MSB b,
TBLACADEMICYEAR_MSB c,
TBLSUBJECTS_MSB d,
TBLEXAMTYPE_MSB e
WHERE
a.EPS_CLASS_ID=b.C_ID
AND a.EPS_SESSION_ID=c.AY_ID
AND a.EPS_SUB_ID=d.S_ID
AND a.EPS_PE_ID=e.E_ID
I want it to return only 1(one) row like
EPS_ID C_NAME AY_YR_NAME S_NAME E_NAME
---------------------------------------------------
7 5 2016-2017 English FA1
I am using the following query but it does not work.
SELECT a.EPS_ID,MAX(b.C_NAME) AS XT,c.AY_YR_NAME,d.S_NAME,e.E_NAME
FROM
TBLEXAMPLANNER_S_MSB a,
TBLCLASS_MSB b,
TBLACADEMICYEAR_MSB c,
TBLSUBJECTS_MSB d,
TBLEXAMTYPE_MSB e
WHERE
a.EPS_CLASS_ID=b.C_ID
AND a.EPS_SESSION_ID=c.AY_ID
AND a.EPS_SUB_ID=d.S_ID
AND a.EPS_PE_ID=e.E_ID
GROUP BY a.EPS_ID,d.S_NAME
The error message is :
Invalid expression in the select list (not contained in either an
aggregate function or the GROUP BY clause)

The usage of GROUP BY makes the engine group the records for you. To do grouping, you have to give advice to the RDBMS for each column, what it should do.
Group it? -> Add column to GROUP BY-Clause
Not group it? -> ok, what else?
ignore the column? remove it from your select-clause
Sum it? -> use SUM(mycol)
other aggregation functions can be found in the documentation
Additionally: In your case you try to group by EPS_ID, which is unique in each row. So a grouping by that column will return all rows, because there is nothing to group by. To group records, they have to have the same value.

Learn to use proper, explicit JOIN syntax.
Your problem is that all unaggregated columns need to be in the GROUP BY:
SELECT a.EPS_ID, MAX(b.C_NAME) AS XT, c.AY_YR_NAME, d.S_NAME, e.E_NAME
FROM TBLEXAMPLANNER_S_MSB a JOIN
TBLCLASS_MSB b
ON a.EPS_CLASS_ID = b.C_ID JOIN
TBLACADEMICYEAR_MSB c
ON a.EPS_SESSION_ID = c.AY_ID JOIN
TBLSUBJECTS_MSB d
ON a.EPS_SUB_ID = d.S_ID JOIN
TBLEXAMTYPE_MSB e
ON a.EPS_PE_ID = e.E_ID
GROUP BY a.EPS_ID, c.AY_YR_NAME, d.S_NAME, e.E_NAME;
Note: I would also recommend that you use table abbreviations for table aliases. So, ep for TBLEXAMPLANNER_S_MSB instead of a. Arbitrary table aliases make the query hard to follow.

Try
SELECT a.EPS_ID,c.AY_YR_NAME,d.S_NAME,e.E_NAME,MAX(b.C_NAME) AS XT ...
GROUP BY 1,2,3,4

Related

Error in using subquery in access join query

I need to use the result of a query as a lookup field for another query. What I tried was using a sub query aliased as something, but finally I got some error saying "enter parameter value" for variz.variz and Y.varizname.
I've searched in forums, but I can't find any similar problem.
SELECT sahmeharkas.attrib,
[sahmeharkas]![expenseper] AS Expense,
variz.variz
FROM sahmeharkas
LEFT JOIN
(SELECT variz.varizname FROM variz GROUP BY variz.varizname) as Y
ON sahmeharkas.attrib = Y.variz.varizname
The table variz does not exist outside of the subquery; you should instead use the subquery alias as the table qualifier, e.g.:
select s.attrib, s.expenseper as expense, y.variz
from
sahmeharkas s left join
(select v.variz, v.varizname from variz v group by v.variz, v.varizname) y on
s.attrib = y.varizname

how to get count of a column along with column from another table

is there any other way for this problem .I wanted to use group by cant use ii.
my solution:
SQL> select (select count(dr_id)
from cus_detail c
where c.dr_id=d.dr_id) as count_cus,dr_name from driver_detail d;
COUNT_CUS DR_NAME
---------- ---------------
1 raju
0 mandi
2 sajuman
3 babu ram coi
0 daju
0 bare babu
use this one.
select count(c.dr_id) as count_cus, d.dr_name
from driver_detail d
inner join cus_detail c on c.dr_id=d.dr_id
group by d.dr_name
I'm not totally sure I understand what you're asking but I think you're asking how to group things and bring in data from another table
I typically prefer to do this as a grouping subquery:
select
d.dr_name,
c.ctr
from
(select dr_id, count(dr_id) ctr from cus_detail group by dr_id) c
INNER JOIN driver_detail d ON c.dr_id=d.dr_id
The reason why here is that by grouping on the id when counting means we can keep a count for two different people (i.e. different id) both called John. If instead we joined on id then grouped on the Name then two different people both called John would have their counts added together
It's also good to group and count in a subquery because sometimes grouping and counting in the outer query introduces wrong counts if three or more tables are related in 1:Many fashion. If a record in a had 3 records in b and 4 records in c, and we join all before we count we will count 12 records. If we group first we will be joining in 1:1 relationship instead and the counter won't inflate erroneously
If two DR_NAME are same then GROUP BY can give different result then what your current query will give.
So better to use an analytical function as the following:
SELECT
COUNT(C.DR_ID) OVER(
PARTITION BY C.DR_ID
) AS COUNT_CUS,
DR_NAME
FROM
DRIVER_DETAIL D
JOIN CUS_DETAIL C ON ( C.DR_ID = D.DR_ID )
Cheers!!
I think you want a basic aggregation query. Your method is correct (although it could be formatted better). The more standard method is join/group by:
select d.dr_name, count(c.dr_id)
from driver_detail d left join
cus_detail c
on c.dr_id = d.dr_id
group by d.dr_name;

How to execute subquery in Oracle? My query gets parentheses erro

I'm trying to execute a query inside LabVIEW so I can informations stored in a Oracle Database, but when a try to execute a query with parenthesis it doesn't works and gives me this erro:
ADO Error: 0x80004005 Exception occured in Microsoft OLE DB Provider for ODBC Drivers: [Oracle][ODBC][Ora]ORA-00907: parêntese direito não encontrado
Here is the SQL query I'm trying to execute:
SELECT
F.CODIGOFAIXAMODELO,
F.CODIGOMODELO,
F.INICIOESCALA,
F.FUNDOESCALA,
F.FAIXA,
F.DESCFAIXA,
F.ORDEM,
P.CODIGOPROCEDIMENTO
FROM FAIXAS F INNER JOIN PROCEDS P ON F.CODIGOFAIXAMODELO=(
SELECT
CODIGOFAIXAMODELO
FROM PROCEDS
WHERE
PROCEDS.CODIGOFAIXAMODELO=F.CODIGOFAIXAMODELO
LIMIT 1
)
WHERE
F.CODIGOMODELO='%CODIGOMODELO%'
ORDER BY F.ORDEM ASC;
The %CODIGOMODELO% is replaced with a value by LabVIEW.
When I try the following Query it works:
SELECT
F.CODIGOFAIXAMODELO,
F.CODIGOMODELO,
F.INICIOESCALA,
F.FUNDOESCALA,
F.FAIXA,
F.DESCFAIXA,
F.ORDEM,
P.CODIGOPROCEDIMENTO
FROM FAIXAS F INNER JOIN PROCEDS P ON F.CODIGOFAIXAMODELO=P.CODIGOFAIXAMODELO
WHERE
F.CODIGOMODELO='%CODIGOMODELO%'
ORDER BY F.ORDEM ASC;
The problem with the second solution is that it returns me many P.CODIGOPROCEDIMENTO, and what I want is to get only one even when there are many.
there is no LIMIT function in Oracle
you need to use ROWNUM = 1 or OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
Also as it is stated by #APC, you shouldn't be joining your table on a subquery.
I would write it this way. It may be more efficient and more readable to avoid trying to evaluate a subquery inside an expression:
SELECT
F.CODIGOFAIXAMODELO,
F.CODIGOMODELO,
F.INICIOESCALA,
F.FUNDOESCALA,
F.FAIXA,
F.DESCFAIXA,
F.ORDEM,
P.CODIGOPROCEDIMENTO
FROM FAIXAS F
INNER JOIN (
SELECT
P1.CODIGOFAIXAMODELO,
MAX(P1.CODIGOPROCEDIMENTO) AS CODIGOPROCEDIMENTO
FROM PROCEDS P1
GROUP BY P1.CODIGOFAIXAMODELO
) P ON P.CODIGOFAIXAMODELO = F.CODIGOFAIXAMODELO
WHERE F.CODIGOMODELO = '%CODIGOMODELO%'
ORDER BY F.ORDEM ASC;
MAX() is an Aggregate Function that will return only one value for each group - specified in the GROUP BY clause. Therefore, using a subquery and joining on CODIGOFAIXAMODELO ensures that only one row is filtered against the main query.
The results really depend on the key structures, datatypes and how many rows are available in PROCEDS. There are of course other, more complex methods to achieve the same result, such as using Analytic Functions.
I think you can write it this way:
SELECT
F.CODIGOFAIXAMODELO,
F.CODIGOMODELO,
F.INICIOESCALA,
F.FUNDOESCALA,
F.FAIXA,
F.DESCFAIXA,
F.ORDEM,
P.CODIGOPROCEDIMENTO
FROM FAIXAS F INNER JOIN PROCEDS P ON F.CODIGOFAIXAMODELO=P.CODIGOFAIXAMODELO and ROWNUM = 1
WHERE
F.CODIGOMODELO='%CODIGOMODELO%'
ORDER BY F.ORDEM ASC;

SQL Syntax Error Group By

I've got a sql syntax and it gives me the error:
Msg 8120, Level 16, State 1, Line 1 Column 'VEHICLEMASTR.cconduction'
is invalid in the select list because it is not contained in either an
aggregate function or the GROUP BY clause.
Here is the SQL syntax:
SELECT A.cplateno,A.cconduction,A.cname,A.cbatterymodel
,A.dbattery,A.DlastChange,A.nlastoilkm,A.naveragekmday
,A.dkmreading,A.dfranacq,A.dfranexp,A.nlimit,A.dreading
,CONVERT(varchar(2),month(MAX(B.dinsexp)))+'/'+CONVERT(varchar(2),day(MAX(B.dinsexp)))+'/'+CONVERT(varchar(4),year(MAX(B.dinsexp))) as dinsexp
,C.corno,CONVERT(varchar(2),month(MAX(C.dregexp)))+'/'+CONVERT(varchar(2),day(MAX(C.dregexp)))+'/'+ CONVERT(varchar(4),year(MAX(C.dregexp))) as dregexp
FROM VEHICLEMASTR A
LEFT JOIN VEHICLEINSURANCE B
ON A.cplateno = B.cplateno
LEFT JOIN VREGISTRATION C
ON A.cplateno = C.cplateno
GROUP BY A.cplateno
Can anybody tell what went wrong?
The "group by" clause must name every column selected, except those columns that are aggregate functions.
FYI an "aggregate" function is one that returns a single value for many rows, like sum(), count(), etc
a.cconduction needs to be in the group by clause.
When using a Group By clause, a column must either have an aggregate function (i.e. COUNT) or be defined in the group by.
A sample group by statement with multiple grouping:
SELECT column1_name, column2_name, aggregate_function(column_name3)
FROM table_name
WHERE column_name1 operator value
GROUP BY column_name1, column_name2;
You must include all fields that you mentioned in your select except the column that has aggregate function so in your case it would be:
GROUP BY
a.cplateno, a.cconduction,a.cname,a.cbatterymodel,a.dbattery,
a.DlastChange,a.nlastoilkm,a.naveragekmday,
a.dkmreading,a.dfranacq,a.dfranexp,a.nlimit,a.dreading
instead of
GROUP BY a.cplateno
Edit:
If you want only the a.cplateno then you don't include the rest of the fields except aggregate function and a.cplateno like:
SELECT A.cplateno
,CONVERT(varchar(2),month(MAX(B.dinsexp)))+'/'+CONVERT(varchar(2),day(MAX(B.dinsexp)))+'/'+CONVERT(varchar(4),year(MAX(B.dinsexp))) as dinsexp
,CONVERT(varchar(2),month(MAX(C.dregexp)))+'/'+CONVERT(varchar(2),day(MAX(C.dregexp)))+'/'+ CONVERT(varchar(4),year(MAX(C.dregexp))) as dregexp
FROM VEHICLEMASTR A
LEFT JOIN VEHICLEINSURANCE B
ON A.cplateno = B.cplateno
LEFT JOIN VREGISTRATION C
ON A.cplateno = C.cplateno
GROUP BY A.cplateno

SQL "Count (Distinct...)" returns 1 less than actual data shows?

I have some data that doesn't appear to be counting correctly. When I look at the raw data I see 5 distinct values in a given column, but when I run an "Count (Distinct ColA)" it reports 4. This is true for all of the categories I am grouping by, too, not just one. E.g. a 2nd value in the column reports 2 when there are 3, a 3rd value reports 1 when there are 2, etc.
Table A: ID, Type
Table B: ID_FK, WorkID, Date
Here is my query that summarizes:
SELECT COUNT (DISTINCT B.ID_FK), A.Type
FROM A INNER JOIN B ON B.ID_FK = A.ID
WHERE Date > 5/1/2013 and Date < 5/2/2013
GROUP BY Type
ORDER BY Type
And a snippet of the results:
4|Business
2|Design
2|Developer
Here is a sample of my data, non-summarized. Pipe is the separator; I just removed the 'COUNT...' and 'GROUP BY...' parts of the query above to get this:
4507|Business
4515|Business
7882|Business
7889|Business
7889|Business
8004|Business
4761|Design
5594|Design
5594|Design
5594|Design
7736|Design
7736|Design
7736|Design
3132|Developer
3132|Developer
3132|Developer
4826|Developer
5403|Developer
As you can see from the data, Business should be 5, not 4, etc. At least that is what my eyes tell me. :)
I am running this inside a FileMaker 12 solution using it's internal ExecuteSQL call. Don't be concerned by that too much, though: the code should be the same as nearly anything else. :)
Any help would be appreciated.
Thanks,
J
Try using a subquery:
SELECT COUNT(*), Type
FROM (SELECT DISTINCT B.ID_FK, A.Type Type
FROM A
INNER JOIN B ON B.ID_FK = A.ID
WHERE Date > 5/1/2013 and Date < 5/2/2013) x
GROUP BY Type
ORDER BY Type
This could be a FileMaker issue, have you seen this post on the FileMaker forum? It describes the same issue (a count distinct smaller by 1) with 11V3 back in 03/2012 with a plug in, then updated with same issue with 12v3 in 11/2012 with ExecuteSQL. It didn't seem to be resolved in either case.
Other considerations might be if there are any referential integrity constraints on the joined tables, or if you can get a query execution plan, you might find it is executing the query differently than expected. not sure if FileMaker can do this.
I like Barmar's suggestion, it would sort twice.
If you are dealing with a bug, directing the COUNT DISTINCT, Join and/or Group By by structuring the query to make them happen at different times might work around it:
SELECT COUNT (DISTINCT x.ID), x.Type
FROM (SELECT A.ID ID, A.Type Type
FROM A
INNER JOIN B ON B.ID_FK = A.ID
WHERE B.Date > 5/1/2013 and B.Date < 5/2/2013) x
GROUP BY Type
ORDER BY Type
you might also try replacing B.ID_FK with A.ID, who knows what context it applies, such as:
SELECT COUNT (DISTINCT A.ID), A.Type