Force Query To Return 0 not null
This is my syntax and it does not return any results, which is accurate, but how can I set it to return a '0' instead of a blank result set? I REALLY need this to take place within a query and not a stored procedure, if at all possible...
Select count(a.empID) As employeeID, b.employeePhone, 'Employee Info' As data
FROM tableMaster b Inner Join tableBadSetup a
ON a.empID = b.empID
Where b.empStatus = 'Leave'
Group By b.employeePhone
select
isnull(employeeID,0) as employeeID,
employeePhone,
data
from
Select count(a.empID) As employeeID, b.employeePhone, 'Employee Info' As data
FROM tableMaster b Inner Join tableBadSetup a
ON a.empID = b.empID
Where b.empStatus = 'Leave'
Group By b.employeePhone
) tt
This shud help..
Thanks,
Jay
<If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'>
Similar Messages
-
OID-Query Entry Return Limit not functioning for OIM
Hi,
I have connected Thor Xellerate (Oracle Identity Manager is the new name) to OID 9i and reconciled users from OID. The Query Entry Return Limit set on OID by default is 1000 and I have 1100 hundred users in OID.
I am able to get all users (means all 1100 users are reconciled) without any problem. I would like to know the significance of this Query Entry Return Limit in this context and whether my understanding is correct or not. Can anybody help me in this regard?
Thanks & Regards,
KrishnaKrishna,
it's interesting that despite the fact that the OID entry return size limit is set to 1000 the reconcile can retrieve 1100 entries. The default behaviour should be that you should see an error msg stating "size limit exceeded". Anyway set the size limit in OID to a higher value just to be on the save side.
regards,
--Olaf -
When Press "Execute Query" LOV return Item not showing
I created a LOV and defined return items.
In the form I created display items, database property NO and assign variable name which is in LOV.
When I enter a new record LOV shows the return item but when I am executing query only database record is showing and I want to show the all item even they are in database or not.
Message was edited by:
Kamranexecute query populates only database items. To populate non database items after execute query, use post query trigger.
-
Named query, primary keys must not contain null
We have an question on the named query. Here is the scenario:
Class JoinClassC (id, name, desc, comment) is mapped to two tables Join_Table_A (id, name, description) and Join_Table_B (id, name, comments); Join_Table_A is the primary table; two tables are associated via primary key.
Defined a named query (findByName, ReadAllQuery/SQL) for JoinClassC descriptor. The sql is:
SELECT a.ID,a.NAME,a.DESCRIPTION,b.COMMENTS FROM JOIN_TABLE_A a, JOIN_TABLE_B b WHERE a.NAME=#name AND a.ID=b.ID AND a.NAME=b.NAME
Getting QueryException while executing the query. Here is the trace:
[3/2/05 13:50:24:795 EST] f8b62aa SystemOut O 2005.03.02 01:50:24.795--ServerSession(738697921)--Thread[Servlet.Engine.Transports : 4,5,main]--Connection(1095574161)--SELECT a.ID,a.NAME,a.DESCRIPTION,b.COMMENTS FROM JOIN_TABLE_A a, JOIN_TABLE_B b WHERE a.NAME='persistence' AND a.ID=b.ID AND a.NAME=b.NAME
2005.03.02 01:50:24.835--ClientSession(1127670417)--Thread[Servlet.Engine.Transports : 4,5,main]--Exception [TOPLINK-6044] (OracleAS TopLink - 10g (9.0.4.4) (Build 040627)): oracle.toplink.exceptions.QueryException
Exception Description: The primary key read from the row [DatabaseRow(
USER04.JOIN_TABLE_B.ID => 2
USER04.JOIN_TABLE_A.NAME => persistence
USER04.JOIN_TABLE_A.DESCRIPTION => FJF Persistence Fram
USER04.JOIN_TABLE_B.COMMENTS => The Persistence Fram)] during the execution of the query was detected to be null. Primary keys must not contain null.
Query: ReadAllQuery(com.ford.it.persistence.unittest.dom.JoinClassC)Local Exception Stack:
Exception [TOPLINK-6044] (OracleAS TopLink - 10g (9.0.4.4) (Build 040627)): oracle.toplink.exceptions.QueryException
Exception Description: The primary key read from the row [DatabaseRow(
USER04.JOIN_TABLE_B.ID => 2
USER04.JOIN_TABLE_A.NAME => persistence
USER04.JOIN_TABLE_A.DESCRIPTION => FJF Persistence Fram
USER04.JOIN_TABLE_B.COMMENTS => The Persistence Fram)] during the execution of the query was detected to be null. Primary keys must not contain null.
Query: ReadAllQuery(com.ford.it.persistence.unittest.dom.JoinClassC)
at oracle.toplink.exceptions.QueryException.nullPrimaryKeyInBuildingObject(QueryException.java:542)
Adding b.ID to the sql select will solve the problem.
Question: does the primary key must be present in the sql select to run this kind of query? Any way to work around the restriction?
Your help would be greatly appreciated.
HaiweiThe problem is that you need to select both primary keys for the multiple table descriptor.
i.e.
SELECT a.ID,a.NAME,a.DESCRIPTION,b.ID, b.COMMENTS FROM JOIN_TABLE_A a, JOIN_TABLE_B b WHERE a.NAME=#name AND a.ID=b.ID AND a.NAME=b.NAME
Your SQL needs to return the same data that TopLink would have selected, which includes the primary key for both tables. TopLink expects both a.ID and b.ID fields in the select, because your only select one and the field names are the same TopLink thought the ID field was for b.ID not a.ID, if you select both it will be ok. -
Script or query to generate a report of null or not null columns
I need a script/query it should pick up all the tables from user_tab_columns and produce a report for all the tables which are the columns are null and not null.
As long as the columns were defined as NOT NULL on table create, or ALTERed NOT NULL, you can do this:
SQL> CREATE TABLE t (id NUMBER NOT NULL, descr VARCHAR2(10));
Table created.
SQL> SELECT column_name, table_name, nullable
2 FROM user_tab_columns
3 WHERE table_name = 'T';
COLUMN_NAME TABLE_NAME N
ID T N
DESCR T Y
SQL> ALTER TABLE t modify (descr NOT NULL);
Table altered.
SQL> SELECT column_name, table_name, nullable
2 FROM user_tab_columns
3 WHERE table_name = 'T';
COLUMN_NAME TABLE_NAME N
ID T N
DESCR T NNote that if you do:
ALTER TABLE t ADD CONSTRAINT id_nn CHECK (id IS NOT NULL);then the nullable column in xxx_tab_columns will remain as Y.
HTH
John -
How to check all items are not null in CAML Query?
HI All,
In a CAML Query, i got three items. In all three items, a particular column(Closure Date) should not be null. How to check in all three items, where 'Closure date' is not null?
Thanks in advance!Hi,
Try this:
"<Where><IsNull><FieldRef Name='Closure Date' /></IsNull></Where>"
Hope it hepls!
Thanks,
Avni Bhatt
If this helped you resolve your issue, please mark it Answered -
Query of Query count(column) returns blank not zero
This appears to be a bug in 7,0,1,116466 and 8,0,1,195765
Query of Query count(column) or count(*) returns blank not
zero when there are no matches. Properly returns a number when
there are query matches.
e.g. select count(i_id) from PersonnelQuery where i_id <
100
Where does one report these?scottcook,
This was a known bug in ColdFusion 6.x which has apparently
not been fixed.
Bug in CF6 (See the Comments section of the page linked
below)
http://livedocs.adobe.com/coldfusion/6.1/htmldocs/using_29.htm
Workaround
http://www.bennadel.com/blog/244-ColdFusion-Query-Of-Queries-Odd-COUNT-Behavior.htm
To report this as a bug
http://www.adobe.com/cfusion/mmform/index.cfm?name=wishform -
Null Pointer exception returned when object is not null!
I've isolated the problem and cut down the code to the minimum. Why do I get a null pointer exception when the start method is called, when the object objJTextField is not null at this point???? I'm really stuck here, HELP!
(two small java files, save as BasePage.java and ExtendedPage.java and then run ExtendedPage)
first file
~~~~~~~
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public abstract class BasePage extends JFrame implements ActionListener
private JPanel objJPanel = null;
public BasePage()
setSize(300,200);
Container objContentPane = getContentPane();
objJPanel = new JPanel();
createObjects();
createPage();
// Add panels to content pane
objContentPane.add(objJPanel);
public void addComponentToPage(JComponent objJComponent)
objJPanel.add(objJComponent);
public void addButtonToPage(JButton objJButton)
objJButton.addActionListener(this);
objJPanel.add(objJButton);
public void actionPerformed(ActionEvent objActionEvent)
System.out.println("Action performed");
userDefinedButtonClicked(objActionEvent.getActionCommand());
// overide
public abstract void createObjects();
public abstract void createPage();
public abstract void userDefinedButtonClicked(String sActionCommand);
file 2
~~~~
import javax.swing.*;
public class ExtendedPage extends BasePage
private JTextField objJTextField = null;
private JButton objJButtonBrowse = null;
public ExtendedPage()
super();
public void createObjects()
objJTextField = new JTextField(20);
objJButtonBrowse = new JButton("Start");
objJButtonBrowse.setActionCommand("START");
public void createPage()
addComponentToPage(objJTextField);
addButtonToPage(objJButtonBrowse);
public void userDefinedButtonClicked(String sActionCommand)
if ((sActionCommand != null) && (sActionCommand.equals("START")) )
start();
private void start()
objJTextField.setText("Doesn't work");
public static void main(String[] args)
ExtendedPage objEP = new ExtendedPage();
objEP.show();Hello ppaulf,
Your problem is in your ExtendedPage.java file. You can fix this by changing the line
private JTextField objJTextField = null;to:
private JTextField objJTextField = new JTextField();This creates a proper instance.
Good luck,
Ming
Developer Technical Support
http://www.sun.com/developers/support -
Do we have a function in oracle to select not null columns at the begining
Hi,
I have 8 columns. Some of them might be null.
I want to display all 8 columns in my result. Not null columns will be first and null at the end.
Here is a sample data :
Employee table :
Employee_id Emp_fname emp_lname emp_mname dept salary emp_height emp_weight
1 aaa ddd d1 100 6 180
2 bbb ccc 120 169
3 dfe d2 5.9 223The expected result is :
result1 result2 result3 result4 result5 result6 result7 result8
1 aaa ddd d1 100 6 180
2 bbb ccc 120 169
3 dfe d2 5.9 223Thanks.
Edited by: BluShadow on 12-Jul-2012 16:12
added {noformat}{noformat} tags for readability. Please read {message:id=9360002} and do this yourself in future.The requirement doesn't make a lot of sense and tends to imply that you have an incorrect data model. If that's the case, you'd be much better off fixing the data model than in trying to write this sort of query (particularly since a poor data model is going to force you to write a bunch of creative SQL).
If you define a type and a function
CREATE TYPE num_tbl AS TABLE OF NUMBER;
create or replace function count_null( l_nums in num_tbl )
return number
is
l_cnt integer := 0;
begin
for i in 1..l_nums.count
loop
if( l_nums(i) is null )
then
l_cnt := l_cnt + 1;
end if;
end loop;
return l_cnt;
end;Then you can do something like this
SQL> ed
Wrote file afiedt.buf
1 select product,
2 coalesce( q1, q2, q3, q4 ) col1,
3 (case when count_null( num_tbl( q1 ) ) = 0
4 then coalesce( q2, q3, q4 )
5 when count_null( num_tbl( q1, q2 ) ) = 1
6 then coalesce( q3, q4 )
7 when count_null( num_tbl( q1, q2, q3 ) ) = 1
8 then q4
9 else null
10 end) col2,
11 (case when count_null( num_tbl( q1, q2 ) ) = 0
12 then coalesce( q3, q4 )
13 when count_null( num_tbl(q1, q2, q3) ) = 1
14 then q4
15 else null
16 end) col3,
17 (case when count_null( num_tbl( q1, q2, q3 ) ) = 0
18 then q4
19 else null
20 end) col4
21* from saleshist
SQL> /
PRODUCT COL1 COL2 COL3 COL4
Oracle EE 100 123 128
Partitioning 100 130 128Justin -
I'm working on a report and one of the fields that I use to pass a parameter shows with no data but it has a length of 1. I can run a query that shows the data that I need if I enter in the criteria 'IS NOT NULL'. Is there a way to pass this value or set the parameter initial value to not null?
OK, if i understand correctly now, the root of the problem is that there is no Team information, but functional group information exists. If this is true, then my first thought is that the root problem lies in data entry, but that is another story.
I think what you want to do is force the team information to come across, even if it has been left out (if functional group information exists). To accomplish this, try adding an outer join to your WHERE clause this way:
WHERE
team(+) = :TEAM
Also, add a NVL around TEAM in the select statement like this:
closeddate,
NVL(team, 'Unknown Team'),
functionalgroup
Depending on the data relationships, you may have to play with the outer joins some to make sure you are returning the correct data set. In fact, now that I think about this, the table you are querying off of is a custom table/view isn't it? The problem then may truly lie in the script used to create the table. There are still some possibilities as to why you are experiencing this problem. If the table/view is a custom table/view, please post the script used to create it. If you have TOAD, open up a schema browser and select the table on the left. This will open up the table on the right hand side. There is a tab across the top labeled 'Scripts'. Copy and paste what is under this tab so I can advise further. If you don't have TOAD, you're going to need another way to find out what tables the data is being pulled from.
Again, my guess is that the field is NULL and Reports is just using a place holder to tell the developer that the field does indeed exist.
Anyway, I hope I've helped shed some light on the problem and that you get some ideas over the weekend!
Good luck,
Steve -
Query to return list of all missing primary key ids from table T1
I found this query online that returns a start and stop for a range of all missing primary key id values from table T1. However i want to rewrite this query to return a whole list of all the missing primary key ids and not a start and stop range. any help plz?
select strt, stp
from (select m.id + 1 as strt,
(select min(id) - 1 from T1 x where x.id > m.id) as stp
from T1 m left outer join T1 r on m.id = r.id - 1 where r.id is null)x where stp is not nullwith t as
select 1 as id from dual union all
select 2 as id from dual union all
select 3 as id from dual union all
select 5 as id from dual union all
select 8 as id from dual union all
select 10 as id from dual union all
select 11 as id from dual union all
select 20 as id from dual
select id_start + level missing_id
from (
select id id_start,
nullif(lead(id) over(order by id) - 1, id) id_end
from t
start with id_end is not null
connect by prior id_start = id_start
and prior dbms_random.random is not null
and level <= id_end - id_start
MISSING_ID
4
6
7
9
12
13
14
15
16
17
18
MISSING_ID
19
12 rows selected.Or:
with t as
select 1 as id from dual union all
select 2 as id from dual union all
select 3 as id from dual union all
select 5 as id from dual union all
select 8 as id from dual union all
select 10 as id from dual union all
select 11 as id from dual union all
select 20 as id from dual
select id_start + level - 1 missing_id
from (
select min(id) id_start,
max(id) id_end
from t
connect by level <= id_end - id_start
minus
select id
from t
MISSING_ID
4
6
7
9
12
13
14
15
16
17
18
MISSING_ID
19
12 rows selected.SY. -
Not Understanding the filter in Explain Plan - filter(NULL IS NOT NULL)
Hi All,
Request your help in understanding the below scenario. (I am not aware of teh application and table details. Just trying to help my friend)
SQL> conn
Enter user-name: [email protected]
Enter password:
Connected.
SQL> select * from v$version;
BANNER
Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bi
PL/SQL Release 10.2.0.3.0 - Production
CORE 10.2.0.3.0 Production
TNS for Linux: Version 10.2.0.3.0 - Production
NLSRTL Version 10.2.0.3.0 - Production
--Checking the count in PO_LINES
SQL> select count(*) from po_lines;
COUNT(*)
0
--PO_LINES is a synonym
SQL> select object_type,owner from dba_objects where object_name = 'PO_LINES';
OBJECT_TYPE OWNER
SYNONYM APPS
--The synonym is pointing to PO.PO_LINES_ALL
SQL> select * from user_synonyms where synonym_name = 'PO_LINES';
SYNONYM_NAME TABLE_OWNER TABLE_NAME DB_LINK
PO_LINES PO PO_LINES_ALL
--But when counting PO.PO_LINES_ALL I am getting different result
SQL> select count(*) c from po.po_lines_all;
C
8828
--Explain plan of teh original query is
SQL> explain plan for
2 select
3 * from po_lines;
Explained.
SQL> select * from table(dbms_xplan.display);
PLAN_TABLE_OUTPUT
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)|
| 0 | SELECT STATEMENT | | 1 | 252 | 0 (0)|
|* 1 | FILTER | | | | |
| 2 | TABLE ACCESS FULL| PO_LINES_ALL | 8796 | 2164K| 106 (4)|
Predicate Information (identified by operation id):
1 - filter(NULL IS NOT NULL)
--Now the object PO.PO_LINES_ALL is TABLE, not an mview.
SQL> select object_type,owner from dba_objects where object_name = 'PO_LINES_ALL';
OBJECT_TYPE OWNER
TABLE POSeek your help in understanding what is happening here.
Thanks in Advance,
jeneeshNext time, prefix with APPS. when you show us the explain plan:
SQL> explain plan for
2 select
3 * from apps.po_lines; -- added the prefix of owner.Just like you prefixed with PO. when you showed us the query on PO_LINES_ALL. It ensures that you are using the synonym which you showed us.
Btw. PO_LINES_ALL, could still be a VIEW given your overview of the situation.
Anyway a filter "NULL IS NOT NULL" is indicative that the optimizer performed something called semantic query optimization (SQO).
SQO is the process of deducing new predicates based upon a) existing predicates in your query (which there is none), b) added predicates to your query (eg. by a VPD policy function), and c) declared constraints on the tables invovled in your query.
A typical example of when a "NOT is NOT NULL" predicate will show up is when for instance in the EMP table there is a declared constraint on EMPNO like this:
check(EMPNO > 0)And your query would hold a predicate that is inconsistent with the constraint, for instance like this:
select *
from EMP
where EMPNO <= 0Oracle will deduce that EMPNO cannot be both greater than zero (constraint) as well as smaller than or equal to zero (your query predicate), and will transform the query into:
select *
from EMP
where EMPNO <= 0
and NULL is NOT NULLThus preventing accessing the EMP table all together, and immediately returning this query with no data found.
Edited by: Toon Koppelaars on Mar 15, 2010 7:17 AM -
Get list of Not Null and PK Columns
hi All,
I need to get the list of all the columns which are part of PK and not null, can you help me on this?
with the below query I am getting the not null ones but need to get the PK columns also
SqlServer Version is 2008R2
SELECT TABLE_CATALOG AS Database_Name, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = 'Express'
AND IS_NULLABLE = 'NO'
Thanks!
NeilGive this a go. It includes by bitval solver function, as the status column is stored that way.
CREATE FUNCTION dbo.solveBitVal(@val BIGINT)
RETURNS @result TABLE (id INT, bitvalue BIGINT)
BEGIN
DECLARE @bitTranslate TABLE (id INT, bitvalue BIGINT)
DECLARE @numbah TABLE (num INT)
DECLARE @loopah INT
SET @loopah = 1
WHILE @loopah <= 63
BEGIN
INSERT INTO @bitTranslate (id, bitvalue) VALUES (@loopah, POWER(CAST(2 AS BIGINT),@loopah-1))
INSERT INTO @numbah (num) VALUES (@loopah)
SET @loopah = @loopah + 1
END
WHILE @val > 0
BEGIN
INSERT INTO @result
SELECT MAX(id), MAX(bitvalue) FROM @bitTranslate WHERE bitvalue <= @val
SELECT @val = @val - MAX(bitvalue) FROM @bitTranslate WHERE bitvalue <= @val
END
RETURN
END
GO
;WITH cons AS (
SELECT o.name, c.*, b.id AS statusID, ROW_NUMBER() OVER (PARTITION BY c.id, colid ORDER BY b.id) AS seq
FROM sys.sysconstraints c
INNER JOIN sys.objects o
ON c.id = o.object_id
CROSS APPLY dbo.solveBitVal(c.status) b
), rCTE AS (
SELECT c.name, c.constid, c.id, c.colid, c.spare1, c.status, c.actions, c.error, CAST(CASE WHEN statusID = 1 THEN 'PRIMARY KEY constraint '
WHEN statusID = 2 THEN 'UNIQUE KEY constraint '
WHEN statusID = 3 THEN 'FOREIGN KEY constraint '
WHEN statusID = 4 THEN 'CHECK constraint '
WHEN statusID = 5 THEN 'DEFAULT constraint '
WHEN statusID = 16 THEN 'Column-level constraint'
WHEN statusID = 32 THEN 'Table-level constraint '
END AS NVARCHAR(MAX)) AS statusName, c.seq, c.statusID
FROM cons c
WHERE seq = 1
UNION ALL
SELECT c.name, c.constid, c.id, c.colid, c.spare1, c.status, c.actions, c.error, CAST(r.statusName + ', ' + CASE WHEN c.statusID = 1 THEN 'PRIMARY KEY constraint '
WHEN c.statusID = 2 THEN 'UNIQUE KEY constraint '
WHEN c.statusID = 3 THEN 'FOREIGN KEY constraint '
WHEN c.statusID = 4 THEN 'CHECK constraint '
WHEN c.statusID = 5 THEN 'DEFAULT constraint '
WHEN c.statusID = 16 THEN 'Column-level constraint'
WHEN c.statusID = 32 THEN 'Table-level constraint '
END AS NVARCHAR(MAX)), c.seq, c.statusID
FROM cons c
INNER JOIN rCTE r
ON c.id = r.id
AND c.colid = r.colid
AND c.seq - 1 = r.seq
SELECT *
FROM rCTE
Don't forget to mark helpful posts, and answers. It helps others to find relevant posts to the same question. -
Hi,
there are many queries my one of my packages, which has the SQL as follows:
Update table XYZ
Set Column A = NULL
Where Colum B IS NOT NULL;
Column B has NUMBER datatype.
Due to 'IS NOT NULL' the index (existing for Column B' is not being used in the above query, leading to Full table scan. Is there any ways of forcing teh index to be picked/used by the query?
Thanks,
Rosalinthansk again for response. Checked the % of the data
fetched by this query and it ranges from 20% to 50
%(varies due to teh fact the table data content could
have different set of data depending on the days
transactions done). So for sure index usage would
help.
Additionally this sql(used in multiple places) come
up in the v$longsops output.
so definitely needs tuning.
Any suggestions?That's not really true though if you understand the mechanisms employed for a full table scan vs an index scan / table lookup (by rowid since the table must also be visited).
Here's something good for you to read
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:4433887271030
A full tablescan reads the table using large sequential reads -- many blocks at a time.
Sequential reads are the fastest type of IO you can do on a disk in general.
An index read will do single block, random IO's. These are generally the slowest you can
do.
I would suggest to you that if you have statistics on the table/indexes that are representative of the data, the Optimizer will be smarter than you (most cases, not all).
Message was edited by:
Tubby -
Oracle 11g:Query to return only 1 to 1 relationship & random selection
Hi
I have a complex query to modify but I have below the sample tables and data with only very few fields(only affected fields).
Query based on 2 tables b_test and s_test.
Pls see below.
create table b_test(building_id number not null,invalid varchar2(1));
create table s_test(sub_building_id number not null,building_id number ,invalid varchar2(1),sequence_no number);
insert into b_test values (1000,'N');
insert into b_test values(2000,'N');
insert into b_test values(3000,'N');
commit;
insert into s_test values(1,1000,'N',90);
insert into s_test values(2,1000,'N',91);
insert into s_test values(3,1000,'N',92);
insert into s_test values(4,1000,'Y',93);
insert into s_test values(5,NULL,'N',NULL);
insert into s_test values(1,2000,'N',94);
insert into s_test values(2,2000,'N',95);
insert into s_test values(3,2000,'N',96);
insert into s_test values(4,2000,'N',97);
insert into s_test values(5,2000,'N',98);
insert into s_test values(6,NULL,'N',NULL);
insert into s_test values(10,3000,'N',99);
insert into s_test values(11,3000,'N',100);
commit;The query below returns all rows required:(also see results:)
select b.building_id,b.invalid,s.sub_building_id,s.sequence_no from b_test b,
(select * from s_test where invalid='N') s
where b.building_id = s.building_id(+)
and b.invalid='N'
Results:
BUILDING_ID INVALID SUB_BUILDING_ID SEQUENCE_NO
1000 N 1 90
1000 N 2 91
1000 N 3 92
2000 N 1 94
2000 N 2 95
2000 N 3 96
2000 N 4 97
2000 N 5 98
3000 N 10 99
3000 N 11 100Now there are 2 requirements:
1)How can the above query be changed so that 1:1 relationship if sub_building_id is returned?i.e For 1 building_id, only show 1 sub_building(This could be a random selection)
(Pls help with query)
The results would be like
BUILDING_ID INVALID SUB_BUILDING_ID SEQUENCE_NO
1000 N 1 90
2000 N 1 94
3000 N 11 1002)How can the same SEQUENCE_NO be shown for all sub_buildings for the same building? (Pls help with query)
The results will be:
BUILDING_ID INVALID SUB_BUILDING_ID SEQUENCE_NO
1000 N 1 90
1000 N 2 90
1000 N 3 90
2000 N 1 94
2000 N 2 94
2000 N 3 94
2000 N 4 94
2000 N 5 94
3000 N 10 99
3000 N 11 99Many thanks!
Edited by: Krithi on 08-Nov-2012 08:48
Edited by: Krithi on 08-Nov-2012 08:55Krithi wrote:
Hi
I have a complex query to modify but I have below the sample tables and data with only very few fields(only affected fields).
Query based on 2 tables b_test and s_test.
Pls see below.
create table b_test(building_id number not null,invalid varchar2(1));
Thanks for posting the CREATE TABLE and INSERT statements, and your existing query; that's very helpful.
The query below returns all rows required:(also see results:)
select b.building_id,b.invalid,s.sub_building_id,s.sequence_no from b_test b,
(select * from s_test where invalid='N') s
where b.building_id = s.building_id(+)
and b.invalid='N'
Results:
BUILDING_ID INVALID SUB_BUILDING_ID SEQUENCE_NO
1000 N 1 90
1000 N 2 91
1000 N 3 92
2000 N 1 94
2000 N 2 95
2000 N 3 96
2000 N 4 97
2000 N 5 98
3000 N 10 99
3000 N 11 100
When I run your query, I get NULL for sequence_no on the last 2 rows, where building_id=3000. The numbers 99 and 100 don't seem to occur in either table. Did you post the worng sample data and/or results?
>
Now there are 2 requirements:
1)How can the above query be changed so that 1:1 relationship if sub_building_id is returned?i.e For 1 building_id, only show 1 sub_building(This could be a random selection)
(Pls help with query) Here's one way:
WITH got_r_num AS
SELECT sub_building_id
, building_id
, sequence_no
, ROW_NUMBER () OVER ( PARTITION BY building_id
ORDER BY sequence_no
) AS r_num
FROM s_test
WHERE invalid = 'N'
SELECT b.building_id
, b.invalid
, r.sub_building_id
, r.sequence_no
FROM b_test b
LEFT OUTER JOIN got_r_num r ON r.building_id = b.building_id
WHERE NVL ( r.r_num
, 1
) = 1
ORDER BY b.building_id
;This is called a Top-N Query , because we're picking N items (N = 1 in this case) from the top of an ordered list. What makes one item the "top", and another one "lower"? That's determined by the analytic ORDER BY clause, in this case
ORDER BY sequence_noThat means the row with the lowest sequence_no (for each building_id) will get r_num=1. If you want a random row from that building_id to be chosen as #1, then you can change the analytic ORDER BY clause to
ORDER BY dbms_random.valueYou can ORDER BY anything you like, even a constant, but you must have an analytic ORDER BY clause. ROW_NUMBER requires an analytic ORDER BY clause.
The results would be like
BUILDING_ID INVALID SUB_BUILDING_ID SEQUENCE_NO
1000 N 1 90
2000 N 1 94
3000 N 11 100
Again, I don't see where the 100 comes from. The results I get are:
BUILDING_ID I SUB_BUILDING_ID SEQUENCE_NO
1000 N 1 90
2000 N 1 94
3000 N 11
2)How can the same SEQUENCE_NO be shown for all sub_buildings for the same building? (Pls help with query)
SELECT b.building_id
, b.invalid
, s.sub_building_id
, MIN (s.sequence_no) OVER ( PARTITION BY s.building_id)
AS seq_no
FROM b_test b
LEFT OUTER JOIN s_test s ON s.building_id = b.building_id
AND s.invalid = 'N'
The results will be:
BUILDING_ID INVALID SUB_BUILDING_ID SEQUENCE_NO
1000 N 1 90
1000 N 2 90
1000 N 3 90
2000 N 1 94
2000 N 2 94
2000 N 3 94
2000 N 4 94
2000 N 5 94
3000 N 10 99
3000 N 11 99
Again, I don't see where you get sequence_no = 99. The results I get are:
BUILDING_ID I SUB_BUILDING_ID SEQ_NO
1000 N 1 90
1000 N 2 90
1000 N 3 90
2000 N 1 94
2000 N 2 94
2000 N 5 94
2000 N 3 94
2000 N 4 94
3000 N 10
3000 N 11Edited by: Frank Kulash on Nov 8, 2012 12:12 PM
Added explanation and results
Edited by: Frank Kulash on Nov 8, 2012 12:28 PM
It looks like you cahnged your sample data from
insert into s_test values(10,3000,'N',NULL);
insert into s_test values(11,3000,'N',NULL);to
insert into s_test values(10,3000,'N',99);
insert into s_test values(11,3000,'N',100);The queries I posted are niow getting 99, like you requested.
Maybe you are looking for
-
Help Needed - Embed File in Projector
Hi All - Hope someone can help. I have a project where I need to create a catalogue. The end projector will be downloaded and has to contain a pre formatted exel spreadsheet which when the user clicks an order now button, the spreadsheet will be laun
-
Calendar invitation emails deleted after accepting
I seems OS X Mail to automatically deletes and erases email invitations for calendar events from the inbox after the user accepts them. They are even removed from the trash, meaning that it is no longer possible to find and view the included message,
-
Compilation error with simple if-else statement
package chapterFive; * Author: Sarab * Filename: MainClass.java * Purpose: Try and get my mind around the concept of the selection * control structures and repetition statements class MainClass { public static void main(String [] args)
-
BADI /CCM/CTLG_ENRICHMENT
Hi all, looking for a bit of help regarding BADI /CCM/CTLG_ENRICHMENT. I have a requirement to take the UNSPSC code from the supplier catalogue and map it to a product category via a look-up in table COMM_CATEGORY. Basically the look-up will consist
-
Importing Multi-Page PDF. Problems with Image Size Changing.
I am working with CS4 on Windows XP. This has happened to numerous files... I open a multi-page PDF using PhotoShop using Grayscale. There are crop marks indicated on each page, so I will use the crop tool to crop each image accordingly. Then I conve