Order of rows retrieved from collection
hi -- If I do not specify an ORDER BY clause when selecting rows from a collection, is
there any pre-defined order in which they'll be returned? (Eg perhaps in the order each
row is added to the collection...)
I ask because I've been using a particular collection for ages, but forgot to specify
an order when querying from it. Just today it returned the rows in a different order
than it has in the past -- only once -- and then they were returned as before.
The order I want -- and have been getting -- is the order in which they're added to the collection.
Will the 'no query transformation' hint accomplish this, or do I need a member that specifies the order?
Thanks,
C
Never mind... got it.
Similar Messages
-
TIPS(64) : ORDERING 된 상위 "N" ROWS 만 RETRIEVE 하는 SQL문
제품 : SQL*PLUS
작성날짜 : 2002-12-20
ORDERING 된 상위 "N" ROWS 만 RETRIEVE 하는 SQL문
===============================================
PURPOSE
다음은 특정 Column 으로 Ordering 된 상위 "n" rows 만 Return 하기 위한
간단한 SQL 문을 소개한다.
Explanation
Example
SELECT *
FROM table A
WHERE n >= (SELECT COUNT(*)
FROM table B
WHERE B.column >= A.column)
ORDER BY column DESC;
예) Emp Table 에서 Salary 가 많은 상위 5명만 구하는 SQL 문
SQL> select empno,ename,sal
2 from emp A
3 where 5 >= (select count(*)
4 from emp B
5 where B.sal >= A.sal)
6 order by sal desc
7 /
EMPNO ENAME SAL
7839 KING 5000
7788 SCOTT 3000
7902 FORD 3000
7566 JONES 2975
7698 BLAKE 2850
5 rows selected.
->Oracle 8i 이상인 경우
다음과 같이 간단히 query 할수 있다.
1 select empno,ename,sal
2 from (select * from emp order by sal desc)
3* where rownum <= 5;
위의 예는 상위 "n" Rows 만 정확히 Return 한다. 그러나 중복된
Column Value 를 가진다면 다음의 예를 고려해 보아야 할 것이다.
SELECT *
FROM table A
WHERE n >= (SELECT COUNT(DISTINCT column)
FROM column B
WHERE B.column >= A.column)
ORDER BY column DESC;
예)
SQL> select empno,ename,sal
2 from emp A
3 where 5 >= (select count(distinct sal)
4 from emp B
5 where B.sal >= A.sal)
6 order by sal desc
7 /
EMPNO ENAME SAL
7839 KING 5000
7788 SCOTT 3000
7902 FORD 3000
7566 JONES 2975
7698 BLAKE 2850
7782 CLARK 2450
6 rows selected.
Reference Documents
none -
EJB ClassCastException Retrieving from Collection in same AppServer
I am experiencing a weired Problem.
I am passing a Collection of IdNameTO Transfer Object from My EJB Client(JSP) to EJB.
At Server Side EJB is able to get the Object From Collection but when it does a Cast to convert the Object back to IdNameTO I get ClassCastException on IdNameTO.
This problem happend only when Both Client and Server(EJB) are deployed on Same Application Server(WebSphere) i.e. same Virtual Machine. If Both Client and EJB are deployed on separate Servers then I don;t get any Exception.
If I form a collection of IdNameTO in EJB and pass it to EJB Client then even on same Server I don't get any exception.I am experiencing a weired Problem.
I am passing a Collection of IdNameTO Transfer Object from My EJB Client(JSP) to EJB.
At Server Side EJB is able to get the Object From Collection but when it does a Cast to convert the Object back to IdNameTO I get ClassCastException on IdNameTO.
This problem happend only when Both Client and Server(EJB) are deployed on Same Application Server(WebSphere) i.e. same Virtual Machine. If Both Client and EJB are deployed on separate Servers then I don;t get any Exception.
If I form a collection of IdNameTO in EJB and pass it to EJB Client then even on same Server I don't get any exception. -
Count rows in a table being retrieved from dba_segments
Hello guys,
I was wondering how can I count the rows in a table that is being retrieved from dba_segments.
-- I am getting the table name from dba_segment
-- Is it possible to count the number of rows in that table at the same time?
-- If not, is there an alternative step without analyzing the table or schema, then getting the result from num_rows in all_tables?
I want the count code to add to the select statement..
SELECT owner, segment_name , segment_type, partition_name, bytes
FROM dba_segments
WHERE owner = UPPER( v_schema )
ORDER BY segment_name;I try to add this to the select statement. count(segment_name), but that did not work.
Any direction(s)?SYS@DEMO102> show user
USER is "SYS"
SYS@DEMO102> l
1 declare
2 counter number;
3 begin
4 for x in (select segment_name, owner
5 from dba_segments
6 where segment_type='TABLE'
7 and owner='SCOTT') loop
8 execute immediate 'select count(*) from '||x.owner||'.'||x.segment_name into counter;
9 dbms_output.put_line(rpad(x.owner,30,' ')
10 ||'.'
11 ||rpad(x.segment_name,30,' ')
12 ||' : '
13 || counter
14 ||' row(s)');
15 end loop;
16* end;
SYS@DEMO102> /
SCOTT .MYTABLE14 : 0 row(s)
SCOTT .TAB3 : 1 row(s)
SCOTT .TAB4 : 4 row(s)
SCOTT .THE_TABLE : 5 row(s)
SCOTT .C : 0 row(s)Nicolas. -
Dears,
After migration(via export/import), we are facing ordering of rows are mis-match in these two databases.
the following same query I am running on the these two databases. but different output. output are below.
[CODE]
SELECT ROWNUM AS RowNo, TBL1.*
FROM ( SELECT COUNT (PG_ID) AS TotalCount,
PG_DESC AS PageDescription,
CURR_EPR_QUEUE AS CurrentQueue,
PG_NME AS PageName,
QUEUE_TYP_CDE AS QueueTypeCode,
PG_ID AS PageID
FROM SASV_TB_CNT_APPL_JUDG_2----this is a view
WHERE (CURR_EPR_QUEUE = 'test' AND QUEUE_TYP_CDE = '01')
OR ( JUD_RACIF_ID = 'test'
AND CMPLTD_IND = '0'
AND DSPLY_IND = '1')
AND TOTAL_CNT > 0
GROUP BY PG_ID,
PG_NME,
PG_DESC,
CURR_EPR_QUEUE,
QUEUE_TYP_CDE
) TBL1
[/CODE]
output- from
Oracle9i Enterprise Edition Release 9.2.0.8.0 - Production
TNS for 32-bit Windows: Version 9.2.0.8.0 - Production
1
7
Other Documents(Hearing)
askinj
HG01_Other_Documents
1
HG01-TB02
2
3
Pending Award
askinj
HG01_Pending_Order
1
HG01-TB05
3
19
Motion(ADR)
askinj
MD01_Motion
1
MD01-TB01
4
5
Other Documents(ADR)
askinj
MD02_Other_Documents
1
MD01-TB02
5
1
Scheduling(ADR)
askinj
MD01_Scheduling
1
MD01-TB03
6
8
Mediations
askinj
MD01_Mediations
1
MD01-TB04
output from--
Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi
TNS for 64-bit Windows: Version 10.2.0.5.0 - Production
1
3
Pending Award
askinj
HG01_Pending_Order
1
HG01-TB05
2
7
Other Documents(Hearing)
askinj
HG01_Other_Documents
1
HG01-TB02
3
8
Mediations
askinj
MD01_Mediations
1
MD01-TB04
4
5
Other Documents(ADR)
askinj
MD02_Other_Documents
1
MD01-TB02
5
1
Scheduling(ADR)
askinj
MD01_Scheduling
1
MD01-TB03
6
19
Motion(ADR)
askinj
MD01_Motion
1
MD01-TB01
the views query is below
SASV_TB_CNT_APPL_JUDG_2
[code]
(SELECT spm.PG_ID,
spm.PG_NME,
spm.PG_DESC,
DECODE (TAJD.ABS_IND, 1, GUEST_JUD_ID, JUDG_ID) CURR_EPR_QUEUE,
QUEUE_TYP_CDE,
1 "TOTAL_CNT",
DECODE (TAJD.ABS_IND, 1, GUEST_JUD_ID, JUDG_ID) JUD_RACIF_ID,
CMLTD_IND CMPLTD_IND,
NULL DSPLY_IND
FROM SA_PG_MSTR SPM, TMST_APPEAL_JUDGE_DETAIL TAJD, SA_WRK_ITM SWI
WHERE SWI.WRK_ITM_ID = TAJD.WRK_ITM_ID
AND swi.tb_pg_id = spm.pg_id
AND SWI.CURR_EPR_QUEUE = 'AppellateCommonJudgeUser'
AND CMLTD_IND = '0'
AND tajd.LEAD_JUD_IND != '3'
UNION ALL
SELECT spm.PG_ID,
spm.PG_NME,
spm.PG_DESC,
CURR_EPR_QUEUE,
QUEUE_TYP_CDE,
1 "TOTAL_CNT",
CURR_EPR_QUEUE judg_racif_id,
'0' CMPLTD_IND,
NULL DSPLY_IND
FROM SA_PG_MSTR spm, SA_WRK_ITM SWI
WHERE SCCS_IND = '1' AND SWI.ACTIVE = '1' AND spm.pg_id = swi.tb_pg_id
UNION ALL
SELECT spm.PG_ID,
spm.PG_NME,
spm.PG_DESC,
CURR_EPR_QUEUE,
QUEUE_TYP_CDE,
1 "TOTAL_CNT",
JUD_RACIF_ID,
CMPLTD_IND,
DSPLY_IND
FROM ST_WRK_ITM_JUD_DTL SWIJD, SA_WRK_ITM SWI, SA_PG_MSTR spm
WHERE SWI.WRK_ITM_ID = SWIJD.WRK_ITM_ID
AND swi.tb_pg_id = spm.pg_id
AND swi.queue_typ_cde IN ('01', '05')
AND swi.dup_ind <> 1);
[code]
parameters in 9i are belows
[code]
aq_tm_processes 1
background_dump_dest D:\oracle\admin\TEST\bdump
compatible 9.2.0.0.0
cursor_sharing similar
db_block_size 8192
db_cache_size 947912704
db_domain
db_file_multiblock_read_count 16
db_keep_cache_size 167772160
db_name TEST
fast_start_mttr_target 300
hash_area_size 1073741824
hash_join_enabled TRUE
instance_name TEST
java_pool_size 67108864
job_queue_processes 10
large_pool_size 109051904
local_listener (ADDRESS=(PROTOCOL=TCP)(HOST=192.168.2.51)(PORT=1521))
log_archive_format %t_%s.dbf
log_archive_start TRUE
log_buffer 26214400
open_cursors 700
optimizer_index_caching 80
optimizer_index_cost_adj 20
optimizer_mode FIRST_ROWS
pga_aggregate_target 1468006400
processes 800
query_rewrite_enabled TRUE
remote_login_passwordfile EXCLUSIVE
session_cached_cursors 400
sga_max_size 2149134244
shared_pool_size 788529152
sort_area_size 1073741824
star_transformation_enabled FALSE
timed_statistics TRUE
undo_management AUTO
undo_retention 10800
undo_tablespace UNDOTBS1
utl_file_dir H:\ICMS_TO_GO
workarea_size_policy AUTO
[code]
parameters in 10 are belows
[code]
aq_tm_processes 1
compatible 10.2.0.5.0
db_block_size 8192
db_domain
db_file_multiblock_read_count 16
db_name TEST
db_recovery_file_dest C:\oracle/flash_recovery_area
db_recovery_file_dest_size 171798691840
dispatchers (PROTOCOL=TCP) (SERVICE=TESTXDB)
job_queue_processes 10
log_archive_format ARC%S_%R.%T
open_cursors 800
open_links 10
open_links_per_instance 10
pga_aggregate_target 3984588800
processes 1200
recyclebin OFF
remote_login_passwordfile EXCLUSIVE
session_cached_cursors 400
sessions 1325
sga_max_size 10485760000
sga_target 10485760000
undo_management AUTO
undo_tablespace UNDOTBS1
utl_file_dir H:\ICMS_TO_GO
optimizer_dynamic_sampling 2
optimizer_features_enable 10.2.0.5
optimizer_index_caching 80
optimizer_index_cost_adj 20
optimizer_mode FIRST_ROWS
optimizer_secure_view_merging FALSE
plsql_optimize_level 2
[code]
where can we look into for this issue? actually we need rows will be the same ordering as it was in 9i.
we are facing this problem in lot of queries, this is a sample one.
Regards
HalimHi Jgarry,
why do you need a particular physical order?
Actually i don't know the .net application behave or code yet . but after migration, I am facing this issue.
one more thing we changed the server machine so Is there any registry parameter (in windows) related to this. Have you any idea.
the application is running since 8 years and I think nobody can rely on implicit data distribution arising from how the data is entered to develop a application.
Hi Hoek,
According to Oracle White Paper(page 17), If I change below parameter. Is there any hope to get same order.
"After you upgrade to Oracle Database 10g, if you
wanted to revert back to 9.2 optimizer behavior you can set
OPTIMIZER_FEATURES_ENABLE = 9.2.0 "
Regards
Halim -
I am wanting to exactly match two ID numbers from two worksheets within the one work book. ID numbers are non linear. Once exactly matched I wish to retrieve a corresponding row value from worksheet two and have it appear in worksheet one against the correct ID number. I have been looking at IF, VLOOKUP, and MATCH functions and suspect that what I want to do requires a combination of two or more. Any help will be greatly appreciated.
regards VaughanhVaughan,
Data A:D is all cells start at column A thru column D.
There is built-in help using the menu item "View > Show Function Browser" in the search field (top right) you can enter vlookup and you will see the detailed description.
From this we see:
VLOOKUP
(search-for, columns-range, return-column, close-match)
search-for: The value to find. search-value can contain any value type.
columns-range: A range of cells. range is a reference to a single range of cells, which may contain values of any type.
return-column: A number that specifies the relative column number of the cell from which to return the value. return-column is a number value. The leftmost column in the range is column 1.
close-match: An optional value that determines whether an exact match is required.
close match (TRUE, 1, or omitted): If there’s no exact match, select the column with the largest top-row value that is less than the search value. Wildcards can’t be used in search-for.
exact match (FALSE or 0): If there’s no exact match, return an error. Wildcards can be used in search-for.
So... the 2,0 means return the value form the same row as the lookup value but from the 2nd column of the range. 3, 0 means from the 3rd column. the ", 0" means exact match -
Number for every record that is retrieved from (query)
Hello
I wish to put a number for every record that is retrieved
from the record that is output by this query
For example
For the first recored/row
Generated number, ksnumber, date
1, gg111 11/05/05
2, oo235 12/06/05
the query returned 2 records 1 and 2 are the number that is
generated with this code.
In addition if there is a built in function, where in the
code do I put it???
<cfquery name="gelov datasource="kl90">
SELECT
FROM
WHERE
ORDER BY
<cfswitch expression="#Form.orderBy#">
<cfks value="KSNUMBER">
KS.KS_NBR
</cfks>
<cfks value="CREATIONDATE">
KS.KREATDAT
</cfks>
</cfswitch>
</cfquery>
<!---html report--->
<cfswitch expression="#Form.outputFormat#">
<cfks value="HTML">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1" />
<title>Ctwye Kss Report</title>
</head>
<style type="text/css">
table{
font-family:Arial, Helvetica, sans-serif;
font-size:10px;
td{
font-family:Arial, Helvetica, sans-serif;
font-size:10px;
th{
font-family:Arial, Helvetica, sans-serif;
font-size:10px;
h2{
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
h3{
font-family:Arial, Helvetica, sans-serif;
font-size:13px;
</style>
<body>
<cfoutput>
<table border="0" cellpadding="3" cellspacing="0">
<tr>
<td align="center">
<h3>Ctwye Kss
Report</h3><br><br></td>
</tr>
<tr>
<td align="center">
</h2>report returned #getCtwyeKss.RecordCount#
records</h2></td>
</tr>
<tr>
<td>
<table border="1" cellpadding="2" cellspacing="0">
<tr>
<td width="160">Ks Number</td>
<td>Creation Date</td>
<!--- <td class="dataField">Address</td>
<td class="dataField">Type</td>
<td class="dataField">Description</td>--->
</tr>
<cfloop query="getCtwyeKss">
<tr bgcolor="<cfif currentrow mod
2>GHOSTWHITE<cfelse>WHITE</cfif>">
<td>#KS_NBR#</td>
<td>#dateformat(KREATDAT,"mm/dd/yyyy")#</td>
</tr>
</cfloop>
</table>
</td>
</tr>
</table>
</BODY>
</HTML>
</cfoutput>
</cfks>
<cfks value="CSV">
<CFHEADER NAME="Content-Disposition" VALUE="attachment;
filename=ctwye.csv">
<cfcontent type="application/msexcel">"Ks
Number","Creation Date"
<cfoutput
query="getCtwyeKss">#ltrim(KS_NBR)#,"#dateformat(KREATDAT,"mm/dd/yyyy")#"
<tr #IIF(getCtwyeKss.CurrentRow MOD
2,DE(''),DE('backgroundColor="##999"'))#>
<!---<tr bgcolor="<cfif currentrow mod
2>##808080<cfelse>##ffffff</cfif>"> --->
</cfoutput>
</cfks>
</cfswitch><cfks> is not a Coldfusion tag. Use <cfcase>
instead.
The following code will print the row numbers
<cfquery name="gelov" datasource="kl90">
select ksnumber, date
from yourTable
</cfquery>
<cfoutput query="gelov">
#currentrow#, #ksnumber#, #date#<br>
</cfoutput> -
Alert about the loading time & Restrict the number of the rows retrieved
Hi everybody, maybe the question is stupid, but I didn't find yet an answer...
I'm using BIP 10.1.3.4.1
Because I have many reports with a huge amount of data to display (in HTML format) and customers once clicked on "View" have to wait a lot of time, they asked me if there is the possibility to do the following things:
1. restrict the number of the rows retrieved (this for each report); this request has to be dynamic (different rows' number for each report and for each user); so, I can't modify the query into the data template in order to retrieve a fixed number of rows;
2. show an alert who says for example " The data loading will take 5 minutes. Do you want to proceed ? YES - NO" This to inform the users how much time they have to wait if they click on Yes.
I checked under the Administrator TAB...but I didn't find nothing "native" about the two questions above.....
So, I ask you if there is a way to activate these features (if they exist "native") or a workaround to implement what I described above.
Any help will be appreciated.
Thanks in advance
AlexHi Vetsrini, thanks for your answer.....but what does it mean ? There are no solutions for my requests ? I remember that Discoverer had the possibility to have an alert as I would like to have with BI Publisher and there was the possibility to choose how many rows it was required from the customer....Is it possible that with BIP is not applicable ?
Have a good day
Alex -
DB row lock from servlet.
Hi to all,
we're developing a J2EE application (with NO Ejb, actually we cannot use them) in which users can select orders from a DB2 database, modify the order, or create a new order. Any order is implemented by a class (Order.java) that exposes methods to execute SELECTs, INSERTs and UPDATEs to the db2 order table; the class mantains a Connection to the database and it's responsible to manage the connection, resultset, prepared statement and so on, and it's possible to specify if we want only read data (executing a select) or read for update the data (so, executing a select ... for update).
Users can access the data via web: the instances of Order are created by a servlet, which load the data and show them passing the Order instance to a JSP that fills up a form.
The problem is we want to lock the row corrisponding to the data mapped into Order instance. Initially, we thought we can instantiate an Order, load data with a select for update, saving on a session the instance, and redirect to the Jsp for visualization, without closing the connection; when the user send data via a form, the order is retrieved from the session, updates are performed and session closed. Unluckily, this approach does not work 'cause the Web Container rolls back automatically all unclosed connection. The row lock is lost.
In very few words, we are trying to keep-alive a Connection after a Servlet method ends. It seems that Servlet specification 2.3 does not allow this, while specification 2.2 does.
How can we avoid this problem ? We cannot just implement an application-level Lock manager, because the database is a legacy database and data are concurrently accessed by legacy applications.
Any suggestion would be very appreciated.
Thanx in advance !
Claudio.Heck (can you say "hec|<" or will the **** filter nuke it?), I had a reply all written up.
And then I noticed you were cross-posting.
Please don't. -
How to Customize the Message "No Row Returned" from a Report
Hi,
I've been trying to customize the Message "No Row Returned" from a Report.
First i followed the instructions in Note:183131.1 -
How to Customize the Message "No Row Returned" from a Report
But of course the OWA_UTIL.REDIRECT_URL in this solution did not work (in a portlet) and i found the metalink document 228620.1 which described how to fix it.
So i followed the "fix" in the document above and now my output is,..
"Portlet 38,70711 responded with content-type text/plain when the client was requesting content-type text/html"
So i search in Metalink for the above and come up with,...
Bug 3548276 PORTLET X,Y RESPONDED WITH CONTENT-TYPE TEXT/PLAIN INSTEAD OF TEXT/HTML
And i've read it and read it and read it and read it and can't make heads or tails of what it's saying.
Every "solution" seems to cause another problem that i have to fix. And all i want to do is customize the Message "No Row Returned" from a Report. Please,...does anyone know how to do this?My guess is that it only shows the number of rows it has retrieved. I believe the defailt is for it to only retrieve 50 rows and as you page through your report it retrieves more. So this would just tell you how many rows was retireved, but probably not how many rows the report would contain if you pages to the end. Oracle doesn't really have a notion of total number of rows until the whole result set has been materialized.
-
DirectAccess Server 2012 Configuration cannot be retrieved from domain controller
Hi everyone,
We are using DirectAccess over Server 2012. There is just one server, no load balancing.
Everything works fine, all clients can connect successfully and operations status page shows all in green. Nevertheless on the dashboard page in the configuration status section it say “Configuration for server [servername] cannot be retrieved
from the domain controller.”
I found a few hints what could cause this problem:
In my case, the RAConfigTask, a scheduled task, was not enabled on the affected WS2012 server (DA entry point in a multisite deployment). After just enabling it, the errors has gone."
http://blog.gocloud-security.ch/2013/01/11/ws2012-directaccess-and-the-configuration-for-server-server-name-retrieved-from-the-domain-controller-cannot-be-applied-error/
Group Policy was filtering out my DA server from the GPO object for some reason. To fix, I opened up Group Policy Management on the domain controller and made sure that my DA server was a part of the group."http://www.joedissmeyer.com/2012/12/more-issues-and-solutions-for.html
Server has no connectivity to the domain in order to update the policies. Run “gpupdate /force” on the server to force policy update. GPO replication might be required in order to retrieve the updated configuration.
This could be because there is no writable domain controller in the Active Directory site of the Remote Access server. http://social.technet.microsoft.com/Forums/en-US/winserverNIS/thread/56fedb17-1274-4e1a-b2d0-fea809f0bc45
I checked everything. Task is enabled and completed successfully, GPO is not filtered out, run gpupdate without any errors, could connect to domain controller, no errors on domain controller, domain controller is writable.
So, I have no idea what could cause this error. Any ideas or hints?
Thanks
Regards
Sebastiani have the exact same problem i figured out that there was a problem with the logon as a service
secpol.msc --> Local Policies --> User Rights Assignement, Logon as a service i have NT Service\All Services
i can acces the group policy via the cpnsole just fine i have not connectivity issues what so ever.
i decided to open a call with microsoft, their suggestion .... we dont know reinstall so i did and here we are same problem and no solution. it is getting frustrating... -
How to preset the order of rows in the outer query of a correlated query ?
Good morning,
I have the following simple query:
select empno,
ename,
sal,
sum(case
when rn = 1 then sal
else -sal
end) over (order by sal, empno) as running_diff
from (
select empno,
ename,
sal,
row_number() over (order by sal, empno) as rn
from emp
where deptno = 10
);That calculates a running difference and uses "row_number() over (...)" which is an Oracle specific feature to do so. It yields the following result (which we will consider correct):
EMPNO ENAME SAL RUNNING_DIFF
7934 MILLER 1300 1300
7782 CLARK 2450 -1150
7839 KING 5000 -6150I wanted to come up with a solution that was not Oracle specific different solution. I tried the following code:
(EDIT: after additional thought, that code is totally different in meaning and will never come close, to the above result. Consider it wrong and ignore this attempt altogether.)
select a.empno,
a.ename,
a.sal,
(select case
when a.empno = min(b.empno) then sum(b.sal)
else sum(-b.sal)
end
from emp b
where b.empno <= a.empno
and b.deptno = a.deptno) as running_diff
from emp a
where a.deptno = 10;but the result is
EMPNO ENAME SAL RUNNING_DIFF
7782 CLARK 2450 2450
7839 KING 5000 -7450
7934 MILLER 1300 -8750which is a long way from the original result. I've tried everything I could think of to order the rows before the running difference is calculated but, have been unsuccessful.
Is there a way to change this second query --(without using Oracle specific features)-- without using windowing features that would yield the same result as the first query ?
Rephrase of the above question:
Is there a way, using plain vanilla SQL (that is aggregate functions and set operations such as joins and unions) to create a query that yields the same result as the first one ?
Also, this is not for production code. This is simply an exercise in set manipulation that I'd like to see a solution for.
Thank you for your help,
John.
Edited by: 440bx - 11gR2 on Jul 18, 2010 12:50 AM - correct "ho w" to "How"
Edited by: 440bx - 11gR2 on Jul 18, 2010 1:42 AM - struck out all references to row_number and windowing features being Oracle specific features.
Edited by: 440bx - 11gR2 on Jul 18, 2010 3:51 AM - Noted that my try is woefully wrong and restated the objective to make it clearer.Hi, John,
One way to get a running total (which is basically what you want) is to do a self-join. Join each row (let's call it the current row, or c) to itself and everything that came before it (let's call this the previous row, or p), and do a regular aggregate SUM, like this:
WITH got_base_sal AS
SELECT deptno
, 2 * MIN (sal) AS base_sal
FROM scott.emp
GROUP BY deptno
SELECT c.deptno
, c.empno
, c.ename
, c.sal
, b.base_sal - SUM (p.sal) AS running_diff
FROM scott.emp c
JOIN scott.emp p ON c.deptno = p.deptno
AND ( c.sal > p.sal
OR ( c.sal = p.sal
AND c.empno >= p.empno
JOIN got_base_sal b ON c.deptno = b.deptno
WHERE c.deptno IN (10)
GROUP BY c.deptno
, c.empno
, c.ename
, c.sal
, b.base_sal
ORDER BY c.deptno
, running_diff DESC
;Output:
DEPTNO EMPNO ENAME SAL RUNNING_DIFF
10 7934 MILLER 1300 1300
10 7782 CLARK 2450 -1150
10 7839 KING 5000 -6150I said you basically want a runninng total. There are two differences between a running total and your requirements
(1) You want to have a total of the negative of what's in the table. That's trivial: use a minus sign.
(2) You want the first item to count as positive instead of negative. That's not so trivial. The query above counts all sals as negative, but adds an offset so that it appears as if the first item had been counted as positive, not negative.
You didn't say what you want to do in case of a tie (two or more rows having the same sal). The query above uses empno as a tie-breaker, so that all sals are calculated as if they were distinct. This is similar to what analytic functions do when the windowing is based on rows. If you want something similar to windowing by range, that might actually be simpler.
The query above calculates a separate running_diff for each deptno, similar to "PARTITION BY deptno" in analytic functions. You happen to be interested in only one deptno right now, but you can change the main query's WHERE clause, or omit it, and the query will still work. If you don't want this feature (analagoud to not having any PARTITION BY), it's easy to modify the query.
You could also get these results using a recursive WITH clause. That meets the criteria of avoiding analytic functions and Oracle-specific features, but not the one about using only plain, simple SQL features. -
Error: The report source could not be retrieved from the state object.
I have been trying to create a report in a JSF page. The relevant parts are below:
Inside the JSP page, this is the code:
<jsp:useBean id="MyBean" class="com.nm.facade.rto.POJOViewerBean" scope="session" />
<jsp:setProperty name="MyBean" property="reportLocation" value="Report1.rpt" />
<v:reportPageViewer reportSource="#{MyBean.reportSource}"
displayToolbarPrintButton="true"
printMode="ActiveX"
zoomPercentage="100"
displayToolbarExportButton="true"
displayToolbarRefreshButton="true"
viewerName="My Viewer"
></v:reportPageViewer>
In the backing bean, this is the relevant code:
public Object getReportSource() throws ReportSDKException
if (propertiesChanged || reportSource == null)
propertiesChanged = false;
if (reportLocation == null)
throw new RuntimeException("The reportLocation property must be set before a report source is retrieved");
ReportClientDocument rcd = new ReportClientDocument();
rcd.setReportAppServer(ReportClientDocument.inprocConnectionString);
rcd.open(reportLocation, 0);
DatabaseController dbc = rcd.getDatabaseController();
//Create the POJO collection and populate it with data
ReportData[] data =
new ReportData("B.B.", "King", 6, new Date(25, 9, 16)),
new ReportData("Muddy", "Waters", 7, new Date(15, 4, 4)),
new ReportData("John Lee", "Hooker", 8, new Date(16, 8, 16)),
new ReportData("Otis", "Rush", 9, new Date(34, 4, 29)),
new ReportData("Buddy", "Guy", 10, new Date(36, 7, 30))
//Create the result set from the collection of POJOs
POJOResultSetFactory factory = new POJOResultSetFactory(ReportData.class);
factory.setVerbose(true);
POJOResultSet results = factory.createResultSet(data);
ResultSetMetaData metaData = results.getMetaData();
//Set the resultset as the report datasource
//Get the table name from the 'Set Datasource Location' dialog in the Crystal Reports designer
String reportTable = "getReportDataDataSource";
dbc.setDataSource(results, reportTable, reportTable);
IReportSource reportSource = rcd.getReportSource();
if (reportSource == null)
throw new RuntimeException("Unable to get a report source.");
return reportSource;
In the CRConfig.xml, this is what is there:
<?xml version="1.0" encoding="utf-8"?>
<CrystalReportEngine-configuration>
<reportlocation>../reports</reportlocation>
<timeout>0</timeout>
<ExternalFunctionLibraryClassNames>
<classname></classname>
</ExternalFunctionLibraryClassNames>
</CrystalReportEngine-configuration>
The report template 'Report1.rpt' is packaged under WEB-INF/reports in the war file.
When I try to generate the report by accessing the JSF page, I am getting an error: "The report source could not be retrieved from the state object. "
I am not sure what is wrong. Can someone help me in resolving this issue?
Edited by: renshai on Jul 9, 2009 3:21 AMMy formatting gets lost and the message looks unintelligible. After some experimentation, I found that if the message exceeds some length, the formatting is removed. Since I couldn't find any way to delete this post, I made another post with the same subject. Please ignore this post and help me to find a solution for the problem posted in the other thread with the same subject. Thanks in advance.
-
Can I use stored procedures to improve data retrieval from the database?
I have been requested to get multiple pieces of data from multiple tables and return the output in an array for use in a Java program.
Eliminating multiple calls to the database. Currently, the data is retrieved from the database in multiple steps but to eliminate
possible bottlenecks in the future, I created several complex sql statements.
For instance,
In the first table there are 20 columns of data. has a column named type which can have the one of these values: line, inn, or bsc
In the second table there are 6 columns of data. has the additional data for type line
In the third table there are 7 columns of data. has the additional data for type inn
In the fourth table there are 2 columns of data. has data regardless of type
etc...
Depending on a specific column value retrieved (inn) from the first table:
I need to collect all 20 columns in the first table and get all the columns in third table and the columns in the fourth table, etc.
Question: How can I remove the duplicate primary key columns without specifying for each table the column names to be returned?
I used the wildcard SELECT * because I didn't want to have to update the retrieval methods if additional columns are added to these
secondary tables.
example of my sql for type inn data:
select * from first_table f, third_table s, fourth_table t
where (f.column1='xxxx' and f.column2='xxxx') (the 'xxxx' are passed into the sql statement)
and
((s.column1=f.column1 and s.column2=f.column2)
and
(f.column3=t.column1));
Currently, I've duplicated the separate sqls for each valid type found in the first table (at least a dozen types). The only difference is
the table name. Instead of the third table I use the second table, etc.
The MAIN Question: How can I set this up to have one sql to handle each type? I want to eliminate having over a dozen duplicated sqls. Can I
incorporate this into a stored procedure or something? If so, how? Can anyone provide sample coding?
Your help is very much appreciated. Thank you.
GDHi, Salah.
Use "Exec" in your query to run procedures.
SAPbobsCOM.Recordset oRS;
oRS = (SAPbobsCOM.Recordset)pCmp.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset);
oRS.DoQuery ("EXEC YourStoredProcName");
Triggers are not supported in SDK.
Regards,
Aleksey -
Vendor batch is retrieved from LIPS-LICHN only if LIPS-LICHN is not blank,
(Current design)
Batch is retrieved from LIPS-CHARG
Vendor batch is retrieved from LIPS-LICHN
(If there is no record in LIPS, blank will be printed out for both fields)
REQUIREMENT:
Batch is retrieved from LIPS-CHARG
Vendor batch is retrieved from LIPS-LICHN only if LIPS-LICHN is not blank.
If LIPS-LICHN is blank, vendor batch is retrieved from LIPS-CHARG.
(If there is no record in LIPS, blank will be printed out for both fields. If both LIPS-CHARG and LIPS-LICHN are blank, blank will be printed out for both fields)
t-lips is the internal table :
DATA: BEGIN OF t_lips OCCURS 0,
vbeln LIKE lips-vbeln, "Delivery document no
posnr LIKE lips-posnr, "Item number for Delivery document
charg LIKE lips-charg, "Batch number
lichn LIKE lips-lichn, "Vendor Batch number
END OF t_lips.
Following is the piece of code:
*& Form f_collect_final
Routine to collect all the display data into the final internal
table t_display.
FORM f_collect_final.
DATA: l_std_pac_no LIKE eket-menge,
l_std_pac_no_out(13) TYPE p,
l_tot_std_pt(13) TYPE c,
l_rmdr(13) TYPE n,
l_qtnt(13) TYPE n,
l_tabix TYPE i.
LOOP AT t_eket.
t_display-ebeln = t_eket-ebeln.
t_display-ebelp = t_eket-ebelp.
t_display-etens = t_eket-etens.
t_display-eindt = t_eket-eindt.
t_display-menge = t_eket-menge.
t_display-meins = t_eket-meins.
t_display-matnr = t_eket-matnr.
mod begin CR1591
t_display-maktx = t_eket-maktx.
READ TABLE t_makt WITH KEY matnr = t_eket-matnr
BINARY SEARCH.
IF sy-subrc = 0.
t_display-maktx = t_makt-maktx.
ENDIF.
mod end CR1591
t_display-vpnam = t_eket-vpnam.
t_display-lifnr = t_eket-lifnr.
t_display-charg = t_eket-charg.
READ TABLE t_mlgn WITH KEY matnr = t_eket-matnr
BINARY SEARCH.
IF sy-subrc = 0.
t_display-lhmg1 = t_mlgn-lhmg1.
t_display-lhme1 = t_mlgn-lhme1.
t_display-lety1 = t_mlgn-lety1.
t_display-ltkze = t_mlgn-ltkze.
ENDIF.
READ TABLE t_marm WITH KEY matnr = t_eket-matnr
BINARY SEARCH.
IF sy-subrc = 0.
t_display-umrez = t_marm-umrez.
t_display-meinh = t_eket-meins.
ENDIF.
READ TABLE t_marc WITH KEY matnr = t_eket-matnr
BINARY SEARCH.
IF sy-subrc = 0.
t_display-zzjp_nyu_sop = t_marc-zzjp_nyu_sop.
t_display-zzjp_dos_frm = t_marc-zzjp_dos_frm.
t_display-zzjp_aprn = t_marc-zzjp_aprn.
t_display-zzjp_re1 = t_marc-zzjp_re1.
ENDIF.
READ TABLE t_lfa1 WITH KEY lifnr = t_eket-lifnr
BINARY SEARCH.
IF sy-subrc = 0.
t_display-name1 = t_lfa1-name1.
ENDIF.
READ TABLE t_lips WITH KEY vbeln = t_eket-vbeln
posnr = t_eket-vbelp
BINARY SEARCH.
l_tabix = sy-tabix.
IF sy-subrc = 0.
t_display-charg = t_lips-charg.(I think this is the place to change).
t_display-lichn = t_lips-charg.
ENDIF.
I have tried with the following code, but it is not working.
IF sy-subrc = 0.
t_display-charg = t_lips-charg.
IF not t_lips-lichn is initial.
t_display-lichn = t_lips-lichn.
ELSE.
t_display-lichn = t_lips-charg.
ENDIF.
ENDIF.Hi,
Find the modification below, consider the bold text and remove the old one:
READ TABLE t_lips WITH KEY vbeln = t_eket-vbeln
posnr = t_eket-vbelp
BINARY SEARCH.
l_tabix = sy-tabix.
IF sy-subrc = 0.
<b>if t_lips-lichn EQ space AND
t_lips-charg NE space.
t_display-charg = t_lips-charg.
t_display-lichn = t_lips-charg.
endif.</b>
<i>t_display-charg = t_lips-charg.(I think this is the place to change).
t_display-lichn = t_lips-charg.</i>ENDIF.
Maybe you are looking for
-
Creation of material characteristics
HI, I have created new material characteristics in CT04, i also created new charc description under material class 001 but enable to creat values for that. it has become greyout. how to enter values. Arati
-
Why are files going offline when exporting from premiere
Hi all I've got a feature length documentary of 2 hours. All files are online but upon exporting from premiere via media encoder the finished file has 'media offline' on some shots. I have NO idea why this is happening. All clips are online on the ti
-
[Solved]Pacman fails on sync
Hello there Archlinux folks! Today, my beloved little home server, running Arch, was a real pain in the ... and I had to realize, the fact: I need the help of ppl who understand this better than I do. As a related matter, I just bought a Network Medi
-
My purchased movies tab on the Apple TV no longer has an "All Purchases" tab. Is there a max number? All of my movies are there in the genre listings, but Apple is screwy in how they list movies. Hellboy I and II are in different categories. RIght no
-
Use of Standard Batch Programs - RFBIBL00 and RFBIBL01
Dear All, I am facing issues while using the standard batch program RFBIBL00 which in turn triggers RFBIBL01 for creating batch session. I understand that there are 3 structures BGR00, BBKPF and BBSEG which needs to be populated. I also understand th