Getting a specified number of rows froma query
How can I get the minimum 3 row from a query after a order by in the select
Eg;
SELECT ROWNUM,ROWID, connection_id, GROUP_ID
FROM prov_pending_commands
ORDER BY group_id
4 AAAZWTAAYAAANMiAAA 680932 32702947
3 AAAZWTAAYAAANMgAAB 644610 32703643
2 AAAZWTAAYAAANLrAAB 51925942 32704602
1 AAAZWTAAYAAANLrAAA 61247803 32704613
I need to get only the group ids 32702947,32703643, 32704602 for some other processing.
I checked by getting rownum or row id, but after ordering it gives wrong data
Please need help
Hi,
Try this,
select * from (select name, row_number() over (order by name) as row_num from test) row_num
where row_num <= 3
If you are looking for something else explain us more with sample output.
Thanks!
M T
Similar Messages
-
Getting a fixed number of rows from various items
Hello,
I am new to Oracle and I am having a hard time resolving this problem. I will try to explain as best as possible.
The application requires that I build a list of items that have been shipped. As they may have various shipping companies, there may be various tracking numbers for each item shipped. The application requires that I get a list of the items that have been shipped that meet certain criteria, then for each item, list the first three tracking numbers that are found. If the shipped item has more than three tracking numbers, the others beyond the third are ignored. I built a SELECT statement using the rownum "column" to limit my result set to a maximum of three. My intention was to build a list of
item ids, then pass those to a stored procedure, then loop for each item id, getting the first three tracking numbers. The tracking numbers returned would be appended to a cursor, which would return the entire set of tracking numbers for the list of item ids.
Any recommendations as to how to approach this requirement would be greatly appreciated. I have gotten through the SELECT that returns the list of item ids. I am having trouble finding the correct approach to getting the three tracking numbers for each item id. One solution was to have the application cycle through each
item id, but I am hoping that this can be done within the stored procedure so that it is called only once for the returned list of item ids.
I wish to thank you in advance. This is all the information I can provide, as I don't have any DDL statements. I hope it will suffice.
Salvador
nullPlease see if you can use something like this:
SELECT a.item, a.tracking_number
FROM table_name a
WHERE 3 >=
(SELECT COUNT (*) + 1
FROM table_name b
WHERE a.item = b.item
AND b.ROWID < a.ROWID
AND b.criteria = 'whatever')
AND a.criteria = 'whatever'
ORDER BY a.item, a.tracking_number
For example, if you have a table named items_shipped that has columns named item, tracking_num, and shipped, and you want all the items that meet the criteria that shipped = 'Y' and the first three tracking_nums for those items, then your query would look something like this:
SELECT a.item, a.tracking_num
FROM items_shipped a
WHERE 3 >=
(SELECT COUNT (*) + 1
FROM items_shipped b
WHERE a.item = b.item
AND b.ROWID < a.ROWID
AND b.shipped = 'Y')
AND a.shipped = 'Y'
ORDER BY a.item, a.tracking_num
You have given very limited information. If the above suggestions are not sufficient, please provide your table structure, including table names, column names, data types and lengths, some sample data, what criteria must be met, and a sample of what you would like the output to be.
null -
Resukt:Get number of rows from 3 different table...?
Hi All,
I need to find out number of rows from 3 different table for the same conditions. Instead of writing 3 queries, is it possible to get it thru one query?
For example, i need to find out number of rows in tables where name = 'Ameet' from 3 different table, i will end writing 3 queries.
1. select count(1) from table_a where name = 'Ameet';
1. select count(1) from table_b where name = 'Ameet';
1. select count(1) from table_c where name = 'Ameet';
Is it possible to write a single query to get result of all above 3 queries?
result:
table_a table_b table_c
34 44 2One way:
SELECT (SELECT COUNT(*) AS CNT FROM TABLE_A WHERE name='Ameet') AS TABLE_A
, (SELECT COUNT(*) AS CNT FROM TABLE_B WHERE name='Ameet') AS TABLE_B
, (SELECT COUNT(*) AS CNT FROM TABLE_C WHERE name='Ameet') AS TABLE_C
FROM DUALIf you want the total:
SELECT SUM(CNT)
FROM
SELECT COUNT(*) AS CNT FROM TABLE_A WHERE name='Ameet'
UNION ALL
SELECT COUNT(*) FROM TABLE_B WHERE name='Ameet'
UNION ALL
SELECT COUNT(*) FROM TABLE_C WHERE name='Ameet'
) -
Getting a specific number of rows
Hi,
I would like to know how to get a specific number of rows. For example, I want to page data in my web application, so I'd like to be able to retrieve just 25 rows in my SELECT statement. I searched and I couldn't see anything under the obvious keywords of LIMIT and TOP (as used by other database vendors) so I'm wondering if possible, what do I need to do - a pointer to the relevant documentation would be helpful also.You can achieve this with rownum
http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14200/pseudocolumns009.htm#i1006297
Best regards
Maxim -
How to get POF object's field value from query result
hi,all:
I want to get field value from the query result, my code is below
Set setResults = cache.entrySet(createFilter("homeAddress.state = 'MA'"));
for (Iterator iter = setResults.iterator(); iter.hasNext(); )
Contact c=(Contact)iter.next();
System.out.println ("firstame####=" + c.getFirstName());
* but I get error*
Exception in thread "main" java.lang.ClassCastException: com.tangosol.util.ConverterCollec
tions$ConverterEntrySet$ConverterEntry cannot be cast to com.oracle.handson.Contact
at com.oracle.handson.QueryExample.printResults(QueryExample.java:159)
at com.oracle.handson.QueryExample.query(QueryExample.java:86)
at com.oracle.handson.QueryExample.main(QueryExample.java:43)
who can tell me how to get POF object's field value from query resultHi,
If you look at the Java Doc for the entrySet method here http://download.oracle.com/docs/cd/E15357_01/coh.360/e15725/com/tangosol/util/QueryMap.html#entrySet_com_tangosol_util_Filter_ you will see that it returns a Set of Map.Entry instances so you need to do this...
Set setResults = cache.entrySet(createFilter("homeAddress.state = 'MA'"));
for (Iterator iter = setResults.iterator(); iter.hasNext(); )
Map.Entry entry = iter.next();
Contact c=(Contact)entry.getValue();
System.out.println ("firstame####=" + c.getFirstName());
}JK -
Fastest way to check total number of rows from View ?
Hello Everyone,
Good Morning !!!!
I am trying to know the exact number of rows from a view.
I have total 262 columns in a view name vw_sample. First column name is col_1 and I do not have permission to view that. but I do have permission to view all other 261 columns. I want to know fastest way to know exact number of rows in this view vw_sample.
How can i know that ?
I tried below things.
1) Tried using COUNT(*) & COUNT(1) but I don't have permission to first column col_1 so that didn't worked.
2) I do not have permission to view DMV "sys.dm_db_partition_stats"
3) I tried to execute below code.
select col_2, col_3,...col_262
into #TempTable
from vw_sample
and it gave me below error
Msg 1105, Level 17, State 2, Line 1
Could not allocate space for object '<temporary system object: 9830433781072176840>'
in database 'tempdb' because the 'PRIMARY' filegroup is full. Create disk space by deleting unneeded files, dropping objects in the filegroup, adding additional files to the filegroup, or setting autogrowth on for existing files in the filegroup.
4) Accidentaly I run below code
select col_2, col_3,...col_262
from vw_sample
It gave me 11 million rows in 40 minutes. As we know this method is not good to test just number of rows from a view.
So what would be my option here ?
Thanks in advance.
Thanks
FredyyFredy, did you try with other column names instead of col1?
SELECT COUNT(col2) FROM View
What difference does that make, than using your column 1.
Please mark as answer, if this has helped you solve the issue.
Good Luck :) .. visit www.sqlsaga.com for more t-sql code snippets and BI related how to articles.
IMO, sqlsaga's answer is the way to go, but you may need to make a minor change. When you do COUNT(<some expression>), SQL counts the number of rows where <some expression> is not NULL. So if col2 can be NULL you need to make a change
so you know what you are counting can't be NULL. If there is some other column in the view that can't be NULL, just count it. Otherwise just use the ISNULL function to convert NULL's to a value. For example, do
Select COUNT(IsNull(col2, 0)) From vw_sample
Note the above assumes that col2 is a type that contains a number (int, numeric, float, etc). If col2 is of a different type, then just replace the 0 in the above with any valid value of the same type as col2 (so '' for varchar, '19000101' for datetime,
etc).
Tom -
Get Number of rows from a sql query.
I am reading data from a sql query in a BLS transaction and I would like to know the number of rows returned.
Is there an easy way to do this without looping through the table?
Thanks JasperHi Jasper,
You can use the XPATH count function similar to this:
GetTagList.Results{count(/Rowsets/Rowset/Row)}
Kind Regards,
Diana Hoppe -
How can I get a fixed number of rows on a SELECT?
I'm interested on get the last xx records of one specific query that returns an higher number of rows than xx. How can I do this?
you can use "where rownum < xx" if you
write "select * from (select ... from ... order by ...) where rownum < 10"
but you can't write "rownum > 10" because no record will be returned.
therefor you have to do like this:
select * from (select ..., rownum as nummer from (select ... from ... order by ...)) where nummer > 10
~
pascal -
Determine number of rows from javascript so I can hide if zero
Hi All,
Found a great article which I adapted to use the link on a report to delete a row in db and remove from table (without a refresh).
It works great except I want the region to not display when there are no rows left.
Currently it shows "No Data Found" but because the page does not submit the region does not hide.
Here is the Java code:
function ackMsg(p_this, p_empno) {
// get the table row on which the user clicked
var tr = $(p_this).closest('tr');
// perform an asynchronous HTTP AJAX request using jQuery
$.ajax({
type: "POST",
url: "wwv_flow.show",
data: {
p_flow_id: $('#pFlowId').val(),
p_flow_step_id: $('#pFlowStepId').val(),
p_instance: $('#pInstance').val(),
x01: p_empno, // assign p_empno to the g_x01 global variable
p_request: "APPLICATION_PROCESS=ack_message" // refer to the application process
beforeSend: // executes while the AJAX call is being processed
function() {
// delete following HTML classes from the table row element
// could be possibly theme dependent
tr.removeClass('even');
tr.removeClass('odd');
// use jQuery's animate function to give the table row, and its children, a red background
tr.children().hover(function() {
tr.children().animate({'backgroundColor': '#00cc00'}, 300);
}, function() {
tr.children().animate({'backgroundColor': '#00cc00'}, 300);
tr.children().animate({'backgroundColor': '#00cc00'}, 300);
success: // to be called if the request succeeds
function() {
jQuery(p_this).trigger('apexrefresh');
// jQuery has difficulties animating inline elements
// that's why we wrap them in a div, which is a block element
tr.children().wrapInner('<div>').children().fadeOut(400, function() {
tr.remove(); // visually remove the row from the report
I did some Googling to add the line ' jQuery(p_this).trigger('apexrefresh');' which refreshes just that report.
What I think I need to do is add a check for number of rows left after the refresh then if = 0 do full page refresh to allow the region condition to hide it.
Unfortunately after hours on Google I can't find how to check how many rows are in the table.
PS the function is called from the link in the report like this onclick="ackMsg(this, #ACK#)"
Please help
AT
Edited by: user1678248 on May 13, 2013 9:39 PM
Edited by: user1678248 on May 13, 2013 9:40 PM1)
When you set a column to hidden in a classic report using the method I described, it creates hidden form elements for that column.
<tt><input type="hidden" name="f01" value="" id="f01_0002"></tt>
You should inspect the source to figure out the name value.
Since this belongs to the wwv_flow form, we can therefore get this data with: wwv_flow.f01
Alternatively, you could have used the apex_item API to achieve the same result, which probably gives a bit better control.
http://docs.oracle.com/cd/E37097_01/doc/doc.42/e35127/apex_item.htm#CHDBFHGA
select apex_item.hidden(1, col) || col col
from table
Set that column to a standard report column so it doesn't escape the html.
You can also reference the data in these fields using PL/SQL using the apex_application API:
http://docs.oracle.com/cd/E37097_01/doc/doc.42/e35127/apex_app.htm#CHDGJBAB
2)
As above, setting the column to hidden creates hidden elements on the page. It is simply f01 because that is the only hidden field I would have on my page. With four reports on the page, you would need to be careful not to do the same on the other reports, as you would get inaccurate data. For each report, setting columns to hidden always starts with f01. In that, you would be best to use the apex_item API.
I actually initially ran into this issue when i had a tabular form on the same page as a report with hidden fields, which was causing conflicts in the page processes.
Hope it helps. -
Deleing large number of rows from table
Hi,
Consider tables A,B,C,D,E,F. all are having 100000++ records Tables B,C,D are dependent on table A (with foreign key constraint). When I am deleting records from all tables, table B,C,D are taking max 30-40 seconds while table A is taking 30-40 mins. All tables are having indexes.
Method I have used:
1. Created Temp table
2. then deleted all records from B,C,D,E,F for all records in temp table for limit of 500.
delete from B where exists (select 1 from temp where b.col1=temp.col1);
3. please suggest options for me why it is taking too much time for deleting records in table A.
Is there any thing that during deleting data from such master table, it is reffering to all dependent tables even if dependent data is not present ??? If yes then couls you please please suggest options for me to remove this ? I hope it won't go for CHECK constraints during deleting data.
Thanks,
Avinash
Edited by: user12952025 on Apr 30, 2013 2:55 AM
Edited by: user12952025 on Apr 30, 2013 2:56 AM
Edited by: user12952025 on Apr 30, 2013 2:57 AMuser12952025 wrote:
Hi,
Consider tables A,B,C,D,E,F. all are having 100000++ records Tables B,C,D are dependent on table A (with foreign key constraint). When I am deleting records from all tables, table B,C,D are taking max 30-40 seconds while table A is taking 30-40 mins. All tables are having indexes.What attribute of the Foreign key is specified? Is it On Delete Cascade? If yes, then in a way, deleting data fro Child tables is un-necessary. Only a Delete from parent shall suffice.
>
Method I have used:
1. Created Temp table
2. then deleted all records from B,C,D,E,F for all records in temp table for limit of 500.
delete from B where exists (select 1 from temp where b.col1=temp.col1);
3. please suggest options for me why it is taking too much time for deleting records in table A.
Is there any thing that during deleting data from such master table, it is reffering to all dependent tables even if dependent data is not present ??? If yes then couls you please please suggest options for me to remove this ? I hope it won't go for CHECK constraints during deleting data.One another way is to "Switch-Off" the relationship while deleting the data.
ALTER TABLE table_name
disable CONSTRAINT constraint_nameAnd then Delete the data from each of tables.
You did specify the number of rows in each table, it would have been better to mention the number of rows to be deleted.
It is not a hard-and-fast way, but would generally perform better, to copy the data (to be retained) from Parent Table into a Temporary Table, Drop Parent Table and rename teh Temporary table to parent table. Similar can be performed on Child tables.
You may then Enable the Foreign key constraints. -
How to find number of rows after query
I have a simple query page. On this page I enter query criteria and hit the go button I get the query result. (say it finds one record)
On processFormRequest of the controler of this page after I execute (executing explicitly because I am using some bind variable too) the query I print getFetchedRowCount() and getRowCount() and I get 10 (as the total records according bind variable criteria are 10). Where I am expecting 1 as the result.
and I want to get the value of that row as well.
Can anyone please guide me how I can achieve this?
ThanksYes I am using queryBean for search region. I can see both, criteria that I am passing through search region and bind variable in the query.
If I pass the customer name it gives me that customer as a result.
but the counts i get doesn't seem to consider that search criteria from query region.
Interestingly when I execute the query again with the same customer name ...I get the correct count. i.e 1
Followoing is the query from "about this page-->business component reference details."
SELECT * FROM
select distinct super_customers.party_name
customer_name,
super_cust.cust_account_id customer_id,
sup_cust_acct.Status,
sup_cust_acct.customer_class_code,
CINT_CRM.Get_Customer_Type(sup_cust_acct.customer_type),
sup_cust_acct.FOB_Point,
sup_cust_acct.sales_channel_code,
From
hz_parties Customers,
hz_parties Super_Customers,
hz_parties cust_cont_rel,
HZ_RELATIONSHIPS REL,
HZ_Cust_Accounts rel_cust_acct,
HZ_Cust_Accounts sup_cust_acct,
HZ_CUST_ACCT_RELATE_ALL Super_Cust
where
customers.party_id = rel.subject_id
and cust_cont_rel.party_id = rel.party_id
and rel_cust_acct.party_id = customers.party_id
and Super_Cust.related_cust_account_id = rel_cust_Acct.cust_account_id
and super_cust.cust_account_id = sup_cust_acct.cust_account_id
and Super_Customers.party_id = sup_cust_acct.party_id
and sup_cust_acct.account_number like 'SC%'
and cust_cont_rel.status = 'A'
and rel.status = 'A'
and rel_cust_acct.status = 'A'
and Super_Cust.status = 'A'
and sup_cust_acct.account_number like nvl(:customerNumber, sup_cust_acct.account_number)
and nvl(rel.object_id, -1) = nvl(nvl(:contactPartyId, rel.object_id), -1)
and upper(super_customers.party_name) like upper(nvl(:customerName, super_customers.party_name))
and sup_cust_acct.account_number like 'SC%') QRSLT
WHERE
(( UPPER(CUSTOMER_NAME) like UPPER(:5)
AND (CUSTOMER_NAME like :6
OR CUSTOMER_NAME like :7
OR CUSTOMER_NAME like :8
OR CUSTOMER_NAME like :9)) -
Select a specific number of rows in query
How can a specific number of rows be selected in a query? For example, a query retrieves 30,000 records and I want to retrieve the output by groups of 5,000. I want the query to retrieve the first 5,000 records, then the next 5,000 records etc. I tried rownum but that does not work.
Thanks,
PANYNot AGAIN. Please...........
Do you know how to Google? Search forum?
Why do you ask this boring FAQ AGAIN?
Sybrand Bakker
Senior Oracle DBA
Experts: Those who know how to search. -
I have used pagination to display the report data.I have used page break.I want to display 10 records on first page and from second page onwards I want to display 25 records on all remaining pages.
I followed this link to show 25 records for all page. "http://www.sqlchick.com/entries/2010/9/11/displaying-fixed-number-of-rows-per-ssrs-report-page.html". Now suggest me how display 10 records only on first page having 25 from second page onwards.Hi mukesh_harkhani,
According to your description, you want to insert page break for different number of rows, display 10 rows on the first page and 25 rows on the following pages. After testing the issue in my SQL Server Reporting Services 2008 environment, we can use the
method below to achieve your requirement:
In your scenario, right-click the group which contains the expression: =CEILING(RowNumber(Nothing)/25) to open the Group Properties dialog box.
Modify the original expression to the following in the Group on textbox:
=Floor((RowNumber(Nothing)+14)/25)
If there are any other questions, please feel free to ask.
Thanks,
Katherine Xiong
Katherine Xiong
TechNet Community Support -
Count number of rows from oracle and sql database and generate a report
Hi All,
Can someone help me in writing a java program for the following scenario?
1. Read the number of rows available from oracle table and print the total row count in a Report.txt text file.
2. Read the number of rows inserted in a sql database (after a specific process-just an information) and print the total row count in the same text file Report.txt .
3. Read the Error Log file (which is generated after a specific process say it has success and failed report for each iterations) and print the number of success and number of failure in the same text file Report.txt .
I need the final Report.txt file in the following format:
1. Oracle table <table name> has 500000 rows.
2. After completion of the specific process 300000 rows were added to SQL table <table name>
Error Log Report:
300000 successfull entries and 200000 failed entries were found from the Error Log file.Thanks for your immediate reply.
I'm just a beginner in java so if i make any mistake please correct and excuse me. :)
This is the code i have for connecting to two different database.
package connectDatabase;
* @author
import java.sql.*;
public class ConnectTo
public void OracleDB()
Connection dbconn;
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
String connString="jdbc:oracle:thin:@SYS_IP:1521:oracl";
dbconn = DriverManager.getConnection(connString, "uname","pwd" );
catch(SQLException sqlex)
sqlex.printStackTrace();
catch(Exception excp)
excp.printStackTrace();
public void SqlDB()
Connection conn;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:connectDB";
conn = DriverManager.getConnection(url,"uname","pwd");
catch (Exception e)
System.err.println("An Exception occured! " +e.getMessage());
}I'm just codding the second half which is for connecting to oracle databse and calculates the row count and displayes in the command prompt.
then connects to SQL database and counts successfull insert in the table.(row count) and displayes on the command prompt.
can you simplify the above code so that i can call the oracleDB() method and SqlDB() method seperately from another calss file using the object of this class?
I'm ok if the report can be seen in a command prompt. FInally i need to calculate the success and failure count from the log file. will let you know once i'm done with codding. -
How do i get my serial number when installing from a disc
i bought the Cs6 from another company, but have all the official licensing. Yet I don't know how to get a serial number. I have an Adobe account, but don't know how to find it either with that.
If you have the installation disc then the serial number should be located on the disc case that the disc comes in.
Find your serial number quickly
Maybe you are looking for
-
Warranty void after repair ?
Dear other iPhone users, Two weeks after taking possession of my iPhone 6 it fell out of my breast pocket flat on the ground, the screen shattered. I blamed myself, and went - here in Kenya where I live and bought the iPhone - to the Apple service re
-
How to switch off orb.properties locally.
Hi, I am using 1.3 J2SE client to run weblogic EJBs. This is working good with sun's JDK. I need to connect to Weblogic from old Silverstream, which is also using working 1.3 Sun's jre, but it has set up it's own ORB in orb.properties (JRE/lib direct
-
Production Order, Operation Release Manually System Status Table:
Hi Expert, 1) i am creating Production Order for only Reporting purpose, we have 38 Operations and it will doing different different users, customers wants to status for Operation what time and date it operation is release, and what time confirm, in
-
Hi, Can someone point me to a blog or article which shows real life scenarios for Context handling functions as I want to practice what I have read. I have already read some articles on these functions(removecontext, usoneasmany etc) and I underst
-
Hello, I want to place a div tag on another one, but I dont want to use position:absolute. So is that possible? PS. When I say on each other I mean like layers.