Where or Having clause and COUNT(1)
I'm having trouble trying to figure out the way to get the conditional difference between two counts in a where clause.
I would like to scan a table and only select records where the record count of one column attribute is different than another.
I have
select name, count(1) from skill <<< TOTAL_COUNT
and
select name, count(1) from skill where score is not NULL <<<< SCORED_COUNT
I want to have a statement that just returns the names for those where TOTAL_COUNT - SCORED_COUNT = 0
... meaning those names where any of the rows have not been scored.
I've tried a "having clause" but it still returns all there names. Even those there TOTAL_COUNT - SCORED_COUNT > 0
Here's the non-working code....
select * from
(select full_name
from emp e
where e.manager = 'Smith, John'
having
((select count(1)
from emp_skill es
where es.emp_fk = e.id
group by null) -
(select count(1)
from emp_skill es1
where es1.emp_fk = e.id and
es1.self_prof is not NULL
group by null)) = 0
)
Don't take 3360 too seriously in this context. COUNT(expression) is a bit of a running joke around these parts.
However, his response does contain the seed of the solution for your problem.
COUNT(<expression>) works because the COUNT function counts all rows with a non-null value for expression. So COUNT('Chocula') counts the non-null occurences of the literal string 'Chocula' in the table. Obviously, this counts every row in the table. COUNT(*) counts all the non-null occurences of a row in the table (even a row with all null values is a row). Clearly these are equivalent.
However, if <expression> evaluates differently for each row, then COUNT(*) and COUNT(<expression>) can differ. So, for your example, assuming that the scored column is truly NULL in some records, what you need is something like:
SQL> SELECT * FROM skill;
NAME SCORE
BOB 5
BOB 6
BOB 7
BILL 5
BILL 8
BILL
SQL> SELECT name, total, scored
2 FROM (SELECT name, count(*) total, count(score) scored
3 FROM skill
4 GROUP BY name)
5 WHERE total <> scored;
NAME TOTAL SCORED
BILL 3 2
Similar Messages
-
Using MODEL clause and COUNT for not numeric data columns....
Hi ,
Is it possible somehow to use the COUNT function to transform a non-numeric data column to a numeric data value (a counter) and be used in a MODEL clause....????
For example , i tried the following in the emp table of SCOTT dataschema with no desired result...
SQL> select deptno , empno , hiredate from emp;
DEPTNO EMPNO HIREDATE
20 7369 18/12/1980
30 7499 20/02/1981
30 7521 22/02/1981
20 7566 02/04/1981
30 7654 28/09/1981
30 7698 01/05/1981
10 7782 09/06/1981
20 7788 18/04/1987
10 7839 17/11/1981
30 7844 08/09/1981
20 7876 21/05/1987
30 7900 03/12/1981
20 7902 03/12/1981
10 7934 23/01/1982
14 rows selected Now , i want to use the MODEL clause in order to 'predict' the number of employees who were going to be hired in the 1990 per deptno...
So , i have constructed the following query which , as expected, does not return the desired results....
SQL> select deptno , month , year , count_
2 from
3 (
4 select deptno , to_number(to_char(hiredate,'mm')) month ,
5 to_number(to_char(hiredate , 'rrrr')) year , count(ename) count_
6 from emp
7 group by deptno , to_number(to_char(hiredate,'mm')) ,
8 to_number(to_char(hiredate , 'rrrr'))
9 )
10 model
11 partition by(deptno)
12 dimension by (month , year)
13 measures (count_ )
14 (
15 count_[1,1990]=count_[1,1982]+count_[11,1982]
16 )
17 /
DEPTNO MONTH YEAR COUNT_
30 5 1981 1
30 12 1981 1
30 2 1981 2
30 9 1981 2
30 1 1990
20 4 1987 1
20 5 1987 1
20 4 1981 1
20 12 1981 1
20 12 1980 1
20 1 1990
10 6 1981 1
10 11 1981 1
10 1 1982 1
10 1 1990 As you see , the measures for the 1990 year is null...because the measure(the count(deptno)) is computed via the group by and not by the MODEL clause...
How should i transform the above query... so as the "count_[1,1982]+count_[11,1982]" will return non-null results per deptno...????
Thanks , a lot
SimonConnected to Oracle Database 10g Express Edition Release 10.2.0.1.0
Connected as hr
SQL>
SQL> SELECT department_id, MONTH, YEAR, count_
2 FROM (SELECT e.department_id
3 ,to_number(to_char(e.hire_date, 'mm')) MONTH
4 ,to_number(to_char(e.hire_date, 'rrrr')) YEAR
5 ,COUNT(e.first_name) count_
6 FROM employees e
7 WHERE e.department_id = 20
8 GROUP BY e.department_id
9 ,to_number(to_char(e.hire_date, 'mm'))
10 ,to_number(to_char(e.hire_date, 'rrrr')));
DEPARTMENT_ID MONTH YEAR COUNT_
20 8 1997 1
20 2 1996 1
SQL> --
SQL> SELECT department_id, MONTH, YEAR, count_
2 FROM (SELECT e.department_id
3 ,to_number(to_char(e.hire_date, 'mm')) MONTH
4 ,to_number(to_char(e.hire_date, 'rrrr')) YEAR
5 ,COUNT(e.first_name) count_
6 FROM employees e
7 WHERE e.department_id = 20
8 GROUP BY e.department_id
9 ,to_number(to_char(e.hire_date, 'mm'))
10 ,to_number(to_char(e.hire_date, 'rrrr')))
11 model
12 PARTITION BY(department_id)
13 dimension BY(MONTH, YEAR)
14 measures(count_)(
15 count_ [1, 1990] = count_ [2, 1996] + count_ [8, 1997]
16 );
DEPARTMENT_ID MONTH YEAR COUNT_
20 8 1997 1
20 2 1996 1
20 1 1990 2
SQL> ---
SQL> SELECT department_id, MONTH, YEAR, count_
2 FROM (SELECT e.department_id
3 ,to_number(to_char(e.hire_date, 'mm')) MONTH
4 ,to_number(to_char(e.hire_date, 'rrrr')) YEAR
5 ,COUNT(e.first_name) count_
6 FROM employees e
7 GROUP BY e.department_id
8 ,to_number(to_char(e.hire_date, 'mm'))
9 ,to_number(to_char(e.hire_date, 'rrrr')))
10 model ignore nav
11 PARTITION BY(department_id)
12 dimension BY(MONTH, YEAR)
13 measures(count_)(
14 count_ [1, 1990] = count_ [2, 1996] + count_ [8, 1997]
15 );
DEPARTMENT_ID MONTH YEAR COUNT_
100 8 1994 2
30 12 1997 1
100 3 1998 1
30 7 1997 1
5 1999 1
30 12 1994 1
30 11 1998 1
30 5 1995 1
100 9 1997 2
100 12 1999 1
30 8 1999 1
1 1990 0
30 1 1990 0
100 1 1990 0
90 9 1989 1
20 8 1997 1
70 6 1994 1
93 rows selected
SQL> -
Hi,
The below result Is retrieved from Table T1(Select * From T1),
ID CODE
101 A1
102 A1
103 A2
104 A1
105 B1
106 B1
107 B5
I want the result like below,
101 A1
102 A1
104 A1
105 B1
106 B1
Can anyone help me to get the expected result.Hi Dhiva !
you can get result with order by clause.
do you want this?
WITH
DATA AS
(select 101 as id, 'A1' val from dual union all
select 102 as id, 'A1' val from dual union all
select 103 as id, 'A2' val from dual union all
select 104 as id, 'A1' val from dual union all
select 105 as id, 'B1' val from dual union all
select 106 as id, 'B1' val from dual union all
SELECT 107 AS ID, 'B5' VAL FROM DUAL)
SELECT * FROM DATA
ORDER by val, id -
Use of Where and having clause
Hi all,
I always have a doubt about use of HAVING and WHERE clause,
suppose I have table T1 with only one column C1
CREATE TABLE T1
(C1 VARCHAR2(1) );
which having data by following INSERT scripts
INSERT INTO T1 VALUES('A');
INSERT INTO T1 VALUES('B');
INSERT INTO T1 VALUES('C');
INSERT INTO T1 VALUES('A');
INSERT INTO T1 VALUES('B');
INSERT INTO T1 VALUES('A');
Now I want result as follows
C1 ==== COUNT(C1)
==============
B ===== 2
A ===== 3
So out of query 1 and 2 which approach is right ?
1) SELECT C1,COUNT(C1) FROM T1
WHERE C1<>'C'
GROUP BY C1
ORDER BY C1 DESC;
2) SELECT C1,COUNT(C1) FROM T1
GROUP BY C1
HAVING C1<>'C'
ORDER BY C1 DESC;
Edited by: user13306874 on Jun 21, 2010 2:36 AMIn SQL, it's always best to filter data at the earliest moment possible.
In your example the WHERE clause would be that moment:
SQL> explain plan for
2 select c1,count(c1)
3 from t1
4 where c1 != 'C'
5 group by c1
6* order by c1 desc;
Explained.
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
Plan hash value: 3946799371
| Id | Operation | Name | Rows | Bytes |
| 0 | SELECT STATEMENT | | 5 | 10 |
| 1 | SORT GROUP BY | | 5 | 10 |
|* 2 | TABLE ACCESS FULL| T1 | 5 | 10 |
Predicate Information (identified by operation id):
2 - filter("C1"!='C')
18 rows selected.
SQL>As you can see the filter is applied during the scan of T1.
Whereas in the HAVING case:
SQL> explain plan for
2 select c1,count(c1)
3 from t1
4 group by c1
5 having c1 != 'C'
6* order by c1 desc;
Explained.
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
Plan hash value: 3146800528
| Id | Operation | Name | Rows | Bytes |
| 0 | SELECT STATEMENT | | 6 | 12 |
|* 1 | FILTER | | | |
| 2 | SORT GROUP BY | | 6 | 12 |
| 3 | TABLE ACCESS FULL| T1 | 6 | 12 |
Predicate Information (identified by operation id):
1 - filter("C1"!='C')
18 rows selected.
SQL>The scan is done after all groups have been computed: one of which was computed in vain, since it will be filtered away due to the HAVING clause.
In general I would use as a guideline: if you are not using aggregate functions in your HAVING clause predicate, then move that predicate to the WHERE portion of your query.
Edited by: Toon Koppelaars on Jun 21, 2010 11:54 AM -
Where clause in COUNT function and joining two queries
I have a table that I am trying to count the number of course passed, and also list the modules passed as well.
the first problem I am having is what to put in the where variable , so that its not specific to a customer(I can use the query below for a particular customer and a particular course)but I will like a generic query where the result will be distinct in terms
of user and course like the one below
select FirstName,LastName,CourseTitle,Noofmodules, count (Coursecompleted) as modulescompleted from EStudentsprogress where Coursecompleted = '1'and EmailAddress = '[email protected]'
and CourseTitle = 'Microsoft MOS 2010 EXCEL' Group by FirstName, LastName, CourseTitle, Noofmodules ;
How can i make it list the result as above, whereby i dont specify the email address or course title(trying to get the result for all the clients )
. Also I have a query that list the courses that is passed by the customer, I will like the column with the list of courses passed be added to the result above, but as a column for each course.
select FirstName,LastName,CourseTitle, EmailAddress, CourseModule as coursepassed from EStudentsprogress where coursecompleted =1
cheersDo you mean this?
select FirstName,
LastName,
CourseTitle,
Noofmodules,
count (Coursecompleted) as modulescompleted,
STUFF((SELECT ',' + CourseTitle
FROM EStudentsprogress
WHERE FirstName = e.FirstName
AND LastName = e.LastName
WHERE Coursecompleted = '1'
FOR XML PATH('')),1,1,'') AS CoursesCompleted
from EStudentsprogress e
where Coursecompleted = '1'
Group by FirstName, LastName, CourseTitle, Noofmodules ;
If not please provide some sample data and explain the output you want
Please Mark This As Answer if it solved your issue
Please Mark This As Helpful if it helps to solve your issue
Visakh
My MSDN Page
My Personal Blog
My Facebook Page
I AM HAVING Incorrect syntax near the keyword 'WHERE'.
It was a typo
try this
select FirstName,
LastName,
CourseTitle,
Noofmodules,
count (Coursecompleted) as modulescompleted,
STUFF((SELECT ',' + CourseTitle
FROM EStudentsprogress
WHERE FirstName = e.FirstName
AND LastName = e.LastName
AND Coursecompleted = '1'
FOR XML PATH('')),1,1,'') AS CoursesCompleted
from EStudentsprogress e
where Coursecompleted = '1'
Group by FirstName, LastName, CourseTitle, Noofmodules ;
Please Mark This As Answer if it solved your issue
Please Mark This As Helpful if it helps to solve your issue
Visakh
My MSDN Page
My Personal Blog
My Facebook Page
its populating all the result for a particular customer, so i added another clause to it and it worked
select FirstName,
LastName,
CourseTitle,
Noofmodules,
count (Coursecompleted) as modulescompleted,
STUFF((SELECT ',' + CourseTitle
FROM EStudentsprogress
WHERE FirstName = e.FirstName
AND LastName = e.LastName
AND Coursecompleted = '1'
AND CourseTitle = e.CourseTitle
FOR XML PATH('')),1,1,'') AS CoursesCompleted
from EStudentsprogress e
where Coursecompleted = '1'
Group by FirstName, LastName, CourseTitle, Noofmodules ;
but the result of the column is long , so i tried to used the course module, which is a column with numbers, and i tried modifying the query , but i had Error converting data type varchar to float.( i checked and saw that stuff is for concatinating
strings) is there a way around it.
i used
select FirstName,
LastName,
CourseModule,
CourseTitle,
Noofmodules,
count (Coursecompleted) as modulescompleted,
STUFF((SELECT ',' + CourseModule
FROM EStudentsprogress
WHERE FirstName = e.FirstName
AND LastName = e.LastName
AND Coursecompleted = '1'
AND CourseTitle = e.CourseTitle
FOR XML PATH('')),1,1,'') AS CoursesCompleted
from EStudentsprogress e
where Coursecompleted = '1'
Group by FirstName, LastName,CourseModule, CourseTitle, Noofmodules ; -
WHERE clause comparing count and RowNumber
Hello, I have just one more question with an error I'm running into. I'm wanting to use a WHERE or HAVING (tried both) to filter the returned data to be between a calculated RowNumber. I tried setting the filter on the tablix or using variables but neither
one worked.I had some help getting the RowNumbers to work now I'm hoping to use that RowNumber to filter the data to only show the data in the middle 80* of what is returned. So what I'm trying to do is use count to find total number of rows. Then filter out
the both 10% and top 90& using that count and then filtered on the RowNumbers.
I tried using different syntax of WHERE and HAVING and I tried putting those clauses under the first WHERE clause or by itself outside of the second select (shown in the example now below). Nothing I've tried works. Is what I'm trying to do possible or is
there another way I could do this if not?
Thanks for the help, much appreciated!
SELECT *,ROW_NUMBER() OVER (ORDER BY TTR) AS RowNumber FROM (
SELECT
FilteredIncidentResolution.incidentid,
FilteredIncident.createdon,
FilteredIncidentResolution.actualend,
FilteredIncident.statecodename,
FilteredIncident.casetypecodename,
FilteredIncidentResolution.timespent,
DATEDIFF(minute, FilteredIncident.createdon, FilteredIncidentResolution.actualend) as TTR
FROM FilteredIncident INNER JOIN
FilteredIncidentResolution ON FilteredIncident.incidentid = FilteredIncidentResolution.incidentid
WHERE (FilteredIncident.statecodename = N'Resolved') AND (FilteredIncident.casetypecodename = N'Support') AND (FilteredIncidentResolution.actualend >= @start) AND
(FilteredIncidentResolution.actualend <= @end)
) X
WHERE RowNumber >= count(FilteredIncidentResolution.incidentid)*.1 AND RowNumber <= count(FilteredIncidentResolution.incidentid)*.9
ORDER BY TTRYou're making the same mistake as before. Calculated column can not be used in the WHERE clause. I think you're actually looking for the NTILE() function, but I will just fix your query:
select * FROM (SELECT *,ROW_NUMBER() OVER (ORDER BY TTR) AS RowNumber FROM (
SELECT
FilteredIncidentResolution.incidentid,
FilteredIncident.createdon,
FilteredIncidentResolution.actualend,
FilteredIncident.statecodename,
FilteredIncident.casetypecodename,
FilteredIncidentResolution.timespent,
DATEDIFF(minute, FilteredIncident.createdon, FilteredIncidentResolution.actualend) as TTR,
COUNT(FilteredIncidentResolution.incidentid)
OVER() as TotalIncidents
FROM FilteredIncident INNER JOIN
FilteredIncidentResolution ON FilteredIncident.incidentid = FilteredIncidentResolution.incidentid
WHERE (FilteredIncident.statecodename = N'Resolved') AND (FilteredIncident.casetypecodename = N'Support') AND (FilteredIncidentResolution.actualend >= @start) AND
(FilteredIncidentResolution.actualend <= @end)
) X
) Y
WHERE RowNumber >= TotalIncidents*.1 AND RowNumber <= TotalIncidents*.9 -- we're excluding top 10 and bottom 10
ORDER BY TTR
For every expert, there is an equal and opposite expert. - Becker's Law
My blog
My TechNet articles -
Which two statements are true about WHERE and HAVING clause ?
Which two statements are true about WHERE and HAVING clause ?
1. WHERE clause can be used to restict rows only
2.HAVING clause can be used to restrict groups only
3.HAVING clause can be used to restrict groups and rows
Plz help me in dis ques...which two will be correct...i think its 1 and 2...but not sure.863180 wrote:
Plz help me in dis ques...which two will be correct...i think its 1 and 2...but not sure.If you are not sure then you do not fully understand HAVING.
SY. -
Use of group by and having clause
hi frnds
can anybody explain me the use of group by an having clause in select state mentHi Rohit,
1. GROUP BY f1 ... fn
2. GROUP BY (itab)
1. GROUP BY f1 ... fn
Effect
Groups database table data in a SELECT command on one line in the result set. A group is a set of lines which all have the same values in each column determined by the field descriptors f1 ... fn.
... GROUP BY f1 ... fn always requires a list in the SELECT clause. If you use field descriptors without an aggregate funciton in the SELECT clause, you must list them in the GROUP BY f1 ... fn clause.
Example
Output the number of passengers, the total weight and the average weight of luggage for all Lufthansa flights on 28.02.1995:
TABLES SBOOK.
DATA: COUNT TYPE I, SUM TYPE P DECIMALS 2, AVG TYPE F.
DATA: CONNID LIKE SBOOK-CONNID.
SELECT CONNID COUNT( * ) SUM( LUGGWEIGHT ) AVG( LUGGWEIGHT )
INTO (CONNID, COUNT, SUM, AVG)
FROM SBOOK
WHERE
CARRID = 'LH' AND
FLDATE = '19950228'
GROUP BY CONNID.
WRITE: / CONNID, COUNT, SUM, AVG.
ENDSELECT.
Note
... GROUP BY f1 ... fn is not supported for pooled and cluster tables.
2. GROUP BY (itab)
Effect
Works like GROUP BY f1 ... fn if the internal table itab contains the list f1 ... fn as ABAP source code. The internal table itab can only have one field. This field must be of the type C and should not be more than 72 characters long. itab must be enclosed in parentheses and there should be no blanks between the parentheses and the table name.
Note
The same restrictions apply to this variant as to GROUP BY f1 ... fn.
Example
Output all Lufthansa departure points with the number of destinations:
TABLES: SPFLI.
DATA: BEGIN OF WA.
INCLUDE STRUCTURE SPFLI.
DATA: COUNT TYPE I.
DATA: END OF WA.
DATA: WA_TAB(72) TYPE C,
GTAB LIKE TABLE OF WA_TAB,
FTAB LIKE TABLE OF WA_TAB,
COUNT TYPE I.
CLEAR: GTAB, FTAB.
WA_TAB = 'COTYFROM COUNT( * ) AS COUNT'. APPEND FTAB.
APPEND WA_TAB TO FTAB.
WA_TAB = 'CITYFROM'.
APPEND WA_TAB TO GTAB.
SELECT DISTINCT (FTAB)
INTO CORRESPONDING FIELDS OF WA
FROM SPFLI
WHERE
CARRID = 'LH'
GROUP BY (GTAB).
WRITE: / WA-CITYFROM, WA-COUNT.
ENDSELECT.
Regards,
Susmitha -
Where clause and order by to DAO classes
Hi
Is it ok(I mean design wise) to pass the 'where clause' conditions and order by clause as a parameter to the method of DAO class?Well, I would suggest you write seperate methods in your dao , one to select data without the where clause and one to select data with the where clause thrown in. If you have different 'where' clauses for selecting different kinds of data, have that many dao methods. The dao methods being specific know exactly what is the data that's coming in.
Lets assume you have a list of purchase orders and each purchase order is indetified by a unique id called PURCHASE_ORDER_ID.
1. The following code would populate a purchase order's details given an id.
private statis final String QUERY_1 = "select * from PURCHASE_ORDERS where PURCHASE_ORDER_ID = ? ";
PurchaseOrderModel getPurchaseOrderData(long poId){
//get a prepared statement from your connection
PreparedStatement pst = conn.prepareStatement(QUERY_1);
//set the poId passed as params to your query
pst.setLong(1, poId);
ResultSet rs = pst.executeQuery();
if(rs.next()){
//populate data into a model
finally{
//clean up resources
return model;
}2. The following code would return a list of PurchaseOrderModel's whose shipping date falls between a set of dates selected by the user.
private statis final String QUERY_2 = "select * from PURCHASE_ORDERS where SHIPPING_DATE between ? and ? ";
PurchaseOrderModel getPurchaseOrdersBetweenDates(list bindValues){
//get a prepared statement from your connection
PreparedStatement pst = conn.prepareStatement(QUERY_1);
//set the dates passed as params to your query
//we know that the List ought to contain only 2 dates
pst.setDate(1, (Date)bindValues.get(0));
pst.setDate(2, (Date)bindValues.get(1));
ResultSet rs = pst.executeQuery();
if(rs.next()){
//iterate and populate data into a model
//add model to a list
finally{
//clean up resources
return list;
3. This is more interesting - the dao method searches a list of Purchase Orders starting with a set of specific words. The words themselves may be one or many. This means that the number of '?' in your prepared statement may be dynamic. Each element of the list is a String that contains the start substring of a purcahse order name. For example - the list may contain elements like ["a", "ab", "c", "gh"] and the dao method returns all purchase order starting with these names.
private statis final String QUERY_3 = "select * from PURCHASE_ORDERS where ";
PurchaseOrderModel getPurchaseOrderNameMatches(list bindValues){
//construct the query dynamically
StringBuffer query = new StringBuffer(QUERY_3);
int count = 0;
for(Iterator itr = bindValues.iterator(); itr.hasNext();;){
String value = (String)itr.next();
query.append ("name like 'value%' ");
if (count != 0 and (count+1 != bindValues.length)){
query.append(" or ");
count ++;
//get a prepared statement from your connection
PreparedStatement pst = conn.prepareStatement(query.toString());
ResultSet rs = pst.executeQuery();
if(rs.next()){
//iterate and populate data into a model
//add model to a list
finally{
//clean up resources
return list;
To sum up,
1. You need as many methods as you have different kinds of searches (one method for each kind of 'where' clause).
2. The ejb/business layer would examine the data and decide on which method to call.
3. Increases coding effort, but makes the code clean and readable. Each layer does it's job. Thus we dont have ejbs forming 'where' clauses and so on.
Having said that, it really is your decision - you should take into consideration the following factors -
1. How big is the project ? If its a huge codebase developed by many people, then segregate the responsibilities clearly in each layer as I have outlined. For a small scale project, you could go with your approach.
2. Whats the take on maintenance and future add-ons ? Do you see the codebase growing with time ?
3. Is your project a commercial one - is it a product that needs to be maintained or is it a one-off development - develop once and you are done with it.
4. What are the design considerations ? Is somebody going to audit code for quality ? Or is it a academic one ?
You should take into account all these before deciding to go one way or the other.
A general thumb rule should be that you should be convinced that your code readable (maintainable), scalable and efficient. Anything that you do towards these ends is good code/design despite what people/books/patterns say, IMO.
cheers,
ram. -
Urgent Group by Having Clause Fails in Oracle and Works in Sybase
Hello EveryBody I need to select curve data of curve whose date is maximum in that curve so say if i ahve
so if records are
curveid curvename curvedate
1001 test1 12/12/1003
1001 test1 12/13/1003
1002 test2 12/12/2002
1002 test2 12/12/2004
I have query which run well in sybase but oracle screw up...My logic say having clause is use to filter the records of group so it should have worked in oracle.....
Here is query
select curveid,curvename from curve group by curveid having curvedate =max(curve_date)
This give "not a Group by " error in oracle....It work well in sybase...
ORA-00979: not a GROUP BY expression
I have query which use subquery to select these records but i don't want that to use that query
Please helpplease understand what I need the result
for each curve i need that data of that curve who date is max in that curve group
so say for 1001 there are two date 1/1/2001 and 1/1/2002
I need the data of curve 1001 with date 1/1/2002
Oracle should have some alternative solution for this....
If i have to use subquery I do have subquery
select a.curveid, b.curvename from curve a group by curveid having curvedate = (select max(curvedate) from curve where a.curveid=b.curveid group by curveid );
I don't want to use that ,,,
I want to solve my probelm using having and group/....
Main purpose of having is to filter the records from group result so IT SHOULD DO THAT WHY ORACLE GIVE ORA ERROR FOR
group by curve_id having curve_date=max(curve_date)
Creators of oracle please reply -
Group by clause and having clause in select
hi frnds
plz give me some information of group by and having clause used in select statement with example
thanksThe Open SQL statement for reading data from database tables is:
SELECT <result>
INTO <target>
FROM <source>
[WHERE <condition>]
[GROUP BY <fields>]
[HAVING <cond>]
[ORDER BY <fields>].
The SELECT statement is divided into a series of simple clauses, each of which has a different part to play in selecting, placing, and arranging the data from the database.
You can only use the HAVING clause in conjunction with the GROUP BY clause.
To select line groups, use:
SELECT <lines> <s1> [AS <a1>] <s2> [AS <a2>] ...
<agg> <sm> [AS <am>] <agg> <sn> [AS <an>] ...
GROUP BY <s1> <s2> ....
HAVING <cond>.
The conditions <cond> that you can use in the HAVING clause are the same as those in the SELECT clause, with the restrictions that you can only use columns from the SELECT clause, and not all of the columns from the database tables in the FROM clause. If you use an invalid column, a runtime error results.
On the other hand, you can enter aggregate expressions for all columns read from the database table that do not appear in the GROUP BY clause. This means that you can use aggregate expressions, even if they do not appear in the SELECT clause. You cannot use aggregate expressions in the conditions in the WHERE clause.
As in the WHERE clause, you can specify the conditions in the HAVING clause as the contents of an internal table with line type C and length 72.
Example
DATA WA TYPE SFLIGHT.
SELECT CONNID
INTO WA-CONNID
FROM SFLIGHT
WHERE CARRID = 'LH'
GROUP BY CONNID
HAVING SUM( SEATSOCC ) > 300.
WRITE: / WA-CARRID, WA-CONNID.
ENDSELECT.
This example selects groups of lines from database table SFLIGHT with the value LH for CARRID and identical values of CONNID. The groups are then restricted further by the condition that the sum of the contents of the column SEATSOCC for a group must be greater than 300.
The <b>GROUP BY</b> clause summarizes several lines from the database table into a single line of the selection.
The GROUP BY clause allows you to summarize lines that have the same content in particular columns. Aggregate functions are applied to the other columns. You can specify the columns in the GROUP BY clause either statically or dynamically.
Specifying Columns Statically
To specify the columns in the GROUP BY clause statically, use:
SELECT <lines> <s1> [AS <a 1>] <s 2> [AS <a 2>] ...
<agg> <sm> [AS <a m>] <agg> <s n> [AS <a n>] ...
GROUP BY <s1> <s 2> ....
To use the GROUP BY clause, you must specify all of the relevant columns in the SELECT clause. In the GROUP BY clause, you list the field names of the columns whose contents must be the same. You can only use the field names as they appear in the database table. Alias names from the SELECT clause are not allowed.
All columns of the SELECT clause that are not listed in the GROUP BY clause must be included in aggregate functions. This defines how the contents of these columns is calculated when the lines are summarized.
Specifying Columns Dynamically
To specify the columns in the GROUP BY clause dynamically, use:
... GROUP BY (<itab>) ...
where <itab> is an internal table with line type C and maximum length 72 characters containing the column names <s 1 > <s 2 > .....
Example
DATA: CARRID TYPE SFLIGHT-CARRID,
MINIMUM TYPE P DECIMALS 2,
MAXIMUM TYPE P DECIMALS 2.
SELECT CARRID MIN( PRICE ) MAX( PRICE )
INTO (CARRID, MINIMUM, MAXIMUM)
FROM SFLIGHT
GROUP BY CARRID.
WRITE: / CARRID, MINIMUM, MAXIMUM.
ENDSELECT.
regards
vinod -
Hi Can anyone please tell me from where I can download the Photoshop CS6 program I purchased a download (media less) some 2 years ago and all has been OK up to know but I am know having issues and would like to uninstall and reinstall. I have the relevant codes and activation keys but would need to be sure I can obtain the program again before I start. Thank you
Make sure you are dealing with the correct product for the serial number. If the serial number is for a full creative suite then you need to get the suite, not the individual application, and vice versa.
Unrelated to that, in case it helps, here is a link to another site. You can download the trial version of the software thru the page linked below and then use your current serial number to activate it.
Be sure to follow the steps outlined in the Note: Very Important Instructions section on the download pages at this site and have cookies enabled in your browser or else the download will not work properly.
CS6: http://prodesigntools.com/adobe-cs6-direct-download-links.html -
Sequence of tables in from clause and sequence of "where clause" conditions
Is Sequence of tables in "From Clause" and sequence of "where clause" conditions matters in 10g for performance?
Edited by: user6763079 on Jun 1, 2011 3:33 AMuser6763079 wrote:
Is Sequence of tables in "From Clause" and sequence of "where clause" conditions matters in 10g for performance?In general it does not matter.
It could matter if the Rule Based Optimizer (RBO) is used. However this RBO is only used if enforced by a hint or if no table statistics are collected. Starting from 10g the table statistics are automatically selected by a regular database job. So in general the CBO would be used.
The CBO will consider different access paths. If the number of tables is low enough, then all possible combinations are considered and the order does not make any difference.
Edited by: Sven W. on Jun 1, 2011 4:00 PM -
Hi all,
How to use the where clause to select records based on condition,,,,, and this condition is based on a date,, for example:
select items from inventory_items
where purchasing_date in :from_date and :to_date;
Thank you very much
TasneemTasneem wrote:
Hi all,
How to use the where clause to select records based on condition,,,,, and this condition is based on a date,, for example:
select items from inventory_items
where purchasing_date in :from_date and :to_date;
Thank you very much
Tasneemtry this..
select items from inventory_items
where purchasing_date between :from_date and :to_date;
If someone's response is helpful or correct, please mark helpful or correct. -
ANSI SQL Syntax - What belongs to join-clause and what to where-clause
Hello,
we currently have a discussion about the ANSI SQL Syntax where we do not agree what belongs to the join clause and what belongs to the where clause in an ANSI Sytnax SQL Query.
Lets say there is a query like this:
+SELECT *+
FROM employees emp, departments dept
WHERE emp.dept_country = dept.dept_country
AND emp.dept_name = dept.dept_name
AND dept.dept_type = 'HQ'
AND emp.emp_lastname = 'Smith'
Primary key of the departments table is on the columns dept_country, dept_name and dept_type. We have a Oracle database 10g.
Now I have rewritten the query to Ansi Syntax:
+SELECT *+
FROM employees emp
JOIN departments dept
ON emp.dept_country = dept.dept_country AND emp.dept_name = dept.dept_name
WHERE dept.dept_type = 'HQ'
AND emp.emp_lastname = 'Smith'
Another developer says that this is not completely correct, every filter on a column that belongs to the primary-key of the joined table has to be in the join clause, like this:
+SELECT *+
FROM employees emp
JOIN departments dept
+ON emp.dept_country = dept.dept_country AND emp.dept_name = dept.dept_name AND dept.dept_type = 'HQ'
WHERE emp.emp_lastname = 'Smith'
Can somebody tell me which on is correct?
Is there any definition for that? I couldn't find it in the Oracle Database definition.
I just found out the names of the ANSI documents here: http://docs.oracle.com/cd/B19306_01/server.102/b14200/ap_standard_sql001.htm#i11939
I had a look at the ANSI webstore but there you have to buy the PDF files. In my case thats exaggerated because both of the Queries work and i am just interessted if there is one correct way.
Thank you in advance
MarcoHi,
As i guideline i would say, answer the question: should the result of the join be filtered or should only filtered rows be joined from a particular table?
This is helpful in the case of outer joins also, for inner joins it doesnt matters as said already be former posters, where there may be hughe semantical differences depending of where the predicates are placed.
From performance view, if we talk about oracle, take a look a the execution plans. You will see that there is (probably) no difference in case of inner joins. Even in case of outer joins the optimizer pushes the predicate as a filter towards the table if it semantically possible.
Regards
Maybe you are looking for
-
please take a look at this SQL statement: select date_column from table1 where to_char(date_column) = '00-000-00' btw i'm using oracle8.. if you use this statement in query analyzer it will return 01-JAN-99 but in sql woksheet it returns 00-000-00. h
-
CAN'T figure out how to make/edit movies in QuickTime Pro...
I can't seem to figure out how to creat and edit movies in Quicktime Pro. I would do this in windows movie maker as its sooo simple, but it doesn't save in a format that works on a mac computer (I'm emailing the video to someone who uses a mac!). And
-
Hello, I have recently experienced this problem opening an .obj file using Photoshop Extended CS6. I have checked About Photoshop, and yes it is the extended version. I have went to the Performance settings, the GPU is not accessible. Scrolling over
-
Wrong condition table for condition type
Hi, I have a big problem during pricing. while creating the sales order the system takes the wrong condition table for the specified condition type (I have created a new condition table and changed the access seq, did the initial load and in customiz
-
Two sided print option is grey out
Recently, I noticed that when I need to print two-sided documents, the "two-sided" print option is greyed out. I have gone into System Preferences Printers & Scanners- and under "options" for the printer enabled the HP Two-sided Printing Accesory (