Selecting top five rows
hi,
pls I have this issue that needs to be resolved. I need to select top five rows from a table depending on the values of a column stock_value. pls I will appreciate if someone can help me out, Francois pls try and help
This is the senerio:
I have a table stock, on the table I have company_name, stock_value, sector.
Now I want to get top five rows from this table depending on the five highest value of stock_value and for each sector.
lets try and write a query that will retrive the records after that I will put it in a procedure.
I know am suppose to ask this on mssql forum but most mssql forums takes time to reply and this is very urgent cos I have to deliver in 45 minutes time
thank you very much
jideofor
hy,
try out:
select s.name, sp. sp_sales total_sales
from salesperson s,
(select salesperson_id,sum(tot_sales) sp_sales
RANK() OVER (ORDER BY SUM(tot_SALES) desc) SALES_RANK
FROM ORDERS
WHERE YEAR = 2006
group by salesperson_id) sp
where sp.sales_rank <= 5 (...n)
and sp.salesperson_id = s.salesperson_id
order by sq.sales_rank;
give result in:
name total_sales
a 100
b 90
c 80
d 70
e 60
hope help you
regards
Similar Messages
-
Hi Guys,
I tried Group By from Select Top 1 Records, As below the script wasn't work.
Please help.
SELECT TOP 1 NR.SHGId, NR.Amount
FROM NEW_DCB_REPORT NR
WHERE NR.SHGId = ND.SHGId
AND NR.ShgMemberId = ND.ShgMemberId
AND NR.LoanNumber = ND.LoanNumber
GROUP BY NR.SHGId,NR.Amount
ORDER BY NR.LedgerNumber DESC
SHGId
SHGMemberId
LoanNumber
Amount
Select Top 1 Row
1028
147852
1
1000
Select Top 1 Row
1028
147853
1
2000
Select Top 1 Row
1028
147854
1
1000
Select Top 1 Row
1028
147855
1
1000
5000
I expected the results are:
SHGId
Amount
1028
5000Yes I did it.
Select SHGId,
SUM(Amount)
amt FROM
SELECT NR.SHGId,
NR.Amount,
, Row_number()
Over(partition
by NR.SHGId,
NR.ShgMemberId , NR.LoanNumber
Order
by NR.LedgerNumber
DESC
) rn
FROM NEW_DCB_REPORT NR
JOIN
NEW_DCB_REPORT ND
ON
NR.SHGId
=
ND.SHGId
AND NR.ShgMemberId
= ND.ShgMemberId
AND NR.LoanNumber
= ND.LoanNumber
) t
Where rn=1
GROUP
BY SHGId
I just changed above the script Partition by add one more column and
[yourNDTable]
Should come NEW_DCB_REPORT table.
However, It shows below the error ,. Please help.
Invalid object name 'NEW_DCB_REPORT'. -
Selecting top x rows for each of the groupby clause
Hi Gurus (again).
I have this query to select the top 24 rows:
select * from
+(+
select proid, to_char((next_day(trunc(request_date, 'iw'), 'mon')-7), 'YYYY') as YEAR, to_char(request_date, 'IW') as WEEK,
next_day(trunc(request_date, 'iw'), 'mon')-7 as weekdate,
trunc(avg(case when report_date > request_date then ((report_date - request_date) * 24) end),1) as avg_ERT_hr, '24' as ERT_goal,
trunc(avg(case when response_date > request_date then ((response_date - request_date) * 24) end),1) as avg_IRT_hr, '48' as IRT_goal,
trunc(avg(case when deliver_date > request_date then ((deliver_date - request_date)) end),1) as avg_IDT_day, '0' as IDT_goal,
trunc(avg(case when complete_date > request_date then ((complete_date - request_date)) end),1) as avg_ORT_day, '0' as ORT_goal
from biw_hda_event
where request_date is not null
group by proid, to_char((next_day(trunc(request_date, 'iw'), 'mon')-7), 'YYYY'), to_char(request_date, 'IW'), next_day(trunc(request_date, 'IW'), 'MON')-7
order by 1 desc, 2 desc
+) where rownum <=24+
The problem here is that I have a group by "proid" clause in addition to the dates. My purpose is to be able to select the top 24 rows for each of the "proid" that is already grouped by the date. Essentially, the top 24 is the last 24 weeks pertaining to that "proid". How can I do this effectively without creating heaps of UNION clause for each of the "proid"?
thanks in advanceI meant to delete this thread, but I do not know how to. Sorry.
-
Selecting top 10 rows based on one column.
Hi,
I need to display the top 10 records for each distinct value of a column.USE Northwind;
-- Solution 1
SELECT S.SupplierID, S.CompanyName, CA.ProductID, CA.UnitPrice
FROM dbo.Suppliers AS S
CROSS APPLY
(SELECT TOP (10) *
FROM dbo.Products AS P
WHERE P.SupplierID = S.SupplierID
ORDER BY UnitPrice DESC, ProductID DESC) AS CA
ORDER BY S.SupplierID, CA.UnitPrice DESC, CA.ProductID DESC;
-- Solution 2
WITH C AS
SELECT S.SupplierID, S.CompanyName, P.ProductID, P.UnitPrice,
ROW_NUMBER() OVER(
PARTITION BY P.SupplierID
ORDER BY P.UnitPrice DESC, P.ProductID DESC) AS RowNum
FROM dbo.Suppliers AS S
JOIN dbo.Products AS P
ON P.SupplierID = S.SupplierID
SELECT SupplierID, CompanyName, ProductID, UnitPrice
FROM C
WHERE RowNum <= 10
ORDER BY SupplierID, ProductID DESC, UnitPrice DESC;
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
Select top 10 rows for each product
Hi,
I have to build a query in the following way:
I have a query like,
select dept, product, product_sold
from products
order by 1, 2 desc
But I have a requirement, not to show all the products in dept . I need to show only first 10 rows of each 'dept' column.
Please help me in acheiving this.You would do something like this (untested):
select dept
, product
, product_sold
from (
select dept
, product
, product_sold
, row_number() over (
partition by dept
order by product
, product_sold
) rn
from products
where rn <= 10;Assuming that I have correctly guessed the ordering you require...
cheers,
Anthony -
how we can select top five records of sal column from emp table.
http://forums.oracle.com/forums/ann.jspa?annID=599
PL/SQL -
Hello,
I was wondering if it was possible to limit the amount of lines selected from a table.
I tried select top n, as it works in SQL, but SAP doesn 't support this syntax..
Is this doesn't work, is there any other way to limit the amount of data selected ?Hi,
Use select upto n rows
Select * from MARA into table ITAB UPTO 10 rows.
select top 10 rows in table.
Regards
SAB -
How to select top one in CDS view ?
I have tried following logic to select top one in CDS view but its giving error -
define view Cds_View_First_Reference as select top one CReferredObject from CDSVIEWCROSSREFHi Ruchi,
since you posted this question in "ABAP in Eclipse" I assume you are asking about CDS in ABAP. This is important because the CDS features sets in ABAP and (native) HANA are different.
Be that as it may,, SELECT TOP 1 is neither supported in the CDS implementation in ABAP nor in HANA.
In ABAP you might consider using the min() or max() function together with the appropriate GROUP BY clause in the CDS view (depending on what you want to achieve), but you can also easily "implement" this in the Open SQL statement which selects from your CDS view.
Using the additions SELECT SINGLE or UP TO 1 ROWS and an appropriate ORDER BY clause in Open SQL, you can achieve the same as SELECT TOP 1.
Unfortunately there is currently no possibility to define a view which delivers the TOP 1 which you can again use in another view ("view on view").
Kind regards
Chris -
ALTERNATIVE FOR 'SELECT TOP STATEMENT
HI FRIENDS
IF ANY ONE KNOWS HOW TO CONVERT THE SQL STATEMENT GIVEN BELOW PLEASE HELP ME
SELECT TOP 1 CardID FROM EasyRechargeMaster WHERE CardGroup = EasyRecharge.CardGroup
THANKS & REGARDSCheck this query. It should give you desired results....Are you sure about that? Does TOP 1 mean "whatever happens to be the first row fetched"?
-
SELECT TOP 1 .... ORDER BY
Hi,
I have the following statement in SQL SERVER:
SELECT TOP 1 NAME FROM STUDENT ORDER BYGRADE
Now, I am trying to translate it ti ORACLE PLSQL, I came up with this statement:
SELECT NAME FROM STUDENT WHERE ROWNUM=1 ORDER BY GRADE
It doesn't work. I guess ORACLE generates ROWNUM before the ORDER BY operation...
How can I have SELECT TOP N ... ORDER BY ... in Oracle the way that I have it in SQL server?
Any help would be apprecited,
AlanCan you cut and paste exactly what you're doing in a SQL*Plus session? It seems to work for me
SCOTT @ hp92 Local> create table t as select * from all_objects;
Table created.
Elapsed: 00:00:08.40
SCOTT @ hp92 Local> desc t;
Name Null? Type
OWNER NOT NULL VARCHAR2(30)
OBJECT_NAME NOT NULL VARCHAR2(30)
SUBOBJECT_NAME VARCHAR2(30)
OBJECT_ID NOT NULL NUMBER
DATA_OBJECT_ID NUMBER
OBJECT_TYPE VARCHAR2(18)
CREATED NOT NULL DATE
LAST_DDL_TIME NOT NULL DATE
TIMESTAMP VARCHAR2(19)
STATUS VARCHAR2(7)
TEMPORARY VARCHAR2(1)
GENERATED VARCHAR2(1)
SECONDARY VARCHAR2(1)
SCOTT @ hp92 Local> create index idx_t on t( object_id );
Index created.
Elapsed: 00:00:00.78
SCOTT @ hp92 Local> analyze table t compute statistics for all indexed columns;
Table analyzed.
Elapsed: 00:00:00.53
SCOTT @ hp92 Local> set autotrace on;
SCOTT @ hp92 Local> select *
2 from (select * from t order by object_id)
3 where rownum < 2;
OWNER OBJECT_NAME SUBOBJECT_NAME
OBJECT_ID DATA_OBJECT_ID OBJECT_TYPE CREATED LAST_DDL_ TIMESTAMP STATUS T G S
SYS DUAL
222 222 TABLE 12-MAY-02 12-MAY-02 2002-05-12:16:20:50 VALID N N N
Elapsed: 00:00:00.13
Execution Plan
0 SELECT STATEMENT Optimizer=CHOOSE
1 0 COUNT (STOPKEY)
2 1 VIEW
3 2 TABLE ACCESS (BY INDEX ROWID) OF 'T'
4 3 INDEX (FULL SCAN) OF 'IDX_T' (NON-UNIQUE)
Statistics
0 recursive calls
0 db block gets
3 consistent gets
1 physical reads
0 redo size
1142 bytes sent via SQL*Net to client
511 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
1 rows processedJustin
Distributed Database Consulting, Inc.
http://www.ddbcinc.com/askDDBC -
Hi to all
Sorry for my english can anyone suggest me how to make a select query which has to display Top - N rows and next -N rows without using rownum.
Ex:
Emp table consists of 100 rows and i have to retrieve records each page consisting of 20 and so on till the end of all records.
Regards,
Naresh Kumar MuraliAm working in Forms and Reports Then try to ask your question under Developer Tools forum.
Nicolas. -
select * from tablename ------always running,but get nothing
select top 1 * from tablename -------get result quickly
select top 2 * from tablename -------get result quickly
select top 14259 * from tablename --------get result quickly
select top 14260 * from tablename --------always running,but get nothing
the thread is:
java.net.SocketInputStream.socketRead0(Native Method)
java.net.SocketInputStream.read(SocketInputStream.java:150)
java.net.SocketInputStream.read(SocketInputStream.java:121)
com.microsoft.sqlserver.jdbc.TDSChannel.read(IOBuffer.java:1782)
com.microsoft.sqlserver.jdbc.TDSReader.readPacket(IOBuffer.java:4838)
- 已锁定com.microsoft.sqlserver.jdbc.TDSReader@54269910
com.microsoft.sqlserver.jdbc.TDSCommand.startResponse(IOBuffer.java:6150)
com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:402)
com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350)
com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
- 已锁定java.lang.Object@320b1499
com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.execute(SQLServerPreparedStatement.java:332)when I run the below sql of Uri Dimant,I get many rows,I think you are right!
Do you have some method to handle this problem?
Or do you have some information for me to Learn?
Thanks a lot.
SELECT
owt.session_id AS waiting_session_id,
owt.blocking_session_id,
DB_NAME(tls.resource_database_id) AS database_name,
(SELECT SUBSTRING(est.[text], ers.statement_start_offset/2
+ 1,
(CASE WHEN ers.statement_end_offset = -1
THEN LEN(CONVERT(nvarchar(max), est.[text])) * 2
ELSE ers.statement_end_offset
END
- ers.statement_start_offset
) / 2)
FROM sys.dm_exec_sql_text(ers.[sql_handle]) AS est) AS waiting_query_text,
CASE WHEN owt.blocking_session_id > 0
THEN (
SELECT
est.[text] FROM sys.sysprocesses AS sp
CROSS APPLY sys.dm_exec_sql_text(sp.[sql_handle]) as est
WHERE sp.spid = owt.blocking_session_id)
ELSE
NULL
END AS blocking_query_text,
(CASE tls.resource_type
WHEN 'OBJECT' THEN OBJECT_NAME(tls.resource_associated_entity_id, tls.resource_database_id)
WHEN 'DATABASE' THEN DB_NAME(tls.resource_database_id)
ELSE (SELECT OBJECT_NAME(pat.[object_id], tls.resource_database_id)
FROM sys.partitions pat WHERE pat.hobt_id = tls.resource_associated_entity_id)
END
) AS object_name,
owt.wait_duration_ms,
owt.waiting_task_address,
owt.wait_type,
tls.resource_associated_entity_id,
tls.resource_description AS local_resource_description,
tls.resource_type,
tls.request_mode,
tls.request_type,
tls.request_session_id,
owt.resource_description AS blocking_resource_description,
qp.query_plan AS waiting_query_plan
FROM sys.dm_tran_locks AS tls
INNER JOIN sys.dm_os_waiting_tasks owt ON tls.lock_owner_address = owt.resource_address
INNER JOIN sys.dm_exec_requests ers ON tls.request_request_id = ers.request_id
AND owt.session_id = ers.session_id
OUTER APPLY sys.dm_exec_query_plan(ers.[plan_handle]) AS qp
GO -
Can SELECT TOP have argument?
Newbie’s question, I believe.
I wanted to make a stored procedure to returns last several rows or last several hundred rows depending on the situation, so I started writing queries in order to copy/paste them into procedure. There are two queries, first works, but
second one shows syntax error in select statement. Can anyone tell me why, and how to go around this?
SELECT TOP 5 * FROM Table1 ORDER BY ID DESC
DECLARE @Counter as int
SET @ Counter = 5
SELECT TOP @ Counter FROM Table1 ORDER BY ID DESCThis works. But I still don?t realize what was wrong with my syntax. Do those () will convert what?s inside parameter to string so parser could read it correctly? What actually is going on here?
It's just the way it is. Originally there was only SELECT TOP n, where the value after TOP had to be a constant. Then they added the ability to have expression, but then they added the parens. This is so that you can say things like:
SELECT TOP (SELECT ... FROM ...) ... FROM
if you feel like.
The old syntax is deprecated but remains for compatibility reasons.
Erland Sommarskog, SQL Server MVP, [email protected] -
Oracle 10g Select Top 100 Percent
Hello
How to convert MS sql 2008 select top 100 query Oracle PL/SQL ? MY sample MSSQL select query
SELECT TOP (100) PERCENT dbo.Operations.OpID, dbo.CompanyInfo.Name AS CompanyName, dbo.CustomerInfo.SubscriberNo, dbo.CustomerInfo.FirstName,
dbo.CustomerInfo.LastName, dbo.Operations.OpDate, dbo.Operations.BillCount, dbo.Operations.TotalAcceptedCash, dbo.Operations.KioskID,
dbo.Operations.ReceiptNo, dbo.Operations.KioskOpID, dbo.KioskInfo.Name AS KioskName, dbo.Operations.TotalBill, dbo.Operations.TotalPayBack,
dbo.CompanyInfo.CompanyID, dbo.Operations.ConfirmedRecord, dbo.PayMethod.ACK AS PayMethod
FROM dbo.Operations INNER JOIN
dbo.CustomerInfo ON dbo.Operations.SubscriberNo = dbo.CustomerInfo.SubscriberNo INNER JOIN
dbo.CompanyInfo ON dbo.Operations.CompanyID = dbo.CompanyInfo.CompanyID INNER JOIN
dbo.KioskInfo ON dbo.Operations.KioskID = dbo.KioskInfo.KioskID INNER JOIN
dbo.PayMethod ON dbo.Operations.PayMethodID = dbo.PayMethod.PayMethodID
ORDER BY dbo.Operations.OpDate DESCHi,
Please read SQL and PL/SQL FAQ
Additionally when you put some code please enclose it between two lines starting with {noformat}{noformat}
i.e.:
{noformat}{noformat}
SELECT ...
{noformat}{noformat}
From what I have found on MS SQL documentation it seems that TOP keyword limits the output to a specified percentage of total number of rows. In your case, having specified 100, you are returning 100% of rows.
So you can simply remove *TOP (100) PERCENT*
Regards.
Al -
Hi,
I want to get the top 10% of salaries in employees table. But I got error:
SQL> select top 10 percent salary
2 from employees
3 order by salary desc;
ORA-00923: FROM keyword not found where expectedHow can I get the top 10% percent?
Thanks a lotHi,
998093 wrote:
... What if I want to get, for example, the employees who are in the top 12% of the salaries? here we cannot use deciles (maybe we can but it won't be very nice).Actually, you can. How nice it will be depends on your data and your exact requirements.
Earlier, we said that the top 10% was the 10th of 10 buckets.
We could say that the top 12% is the last 12 of 100 buckets:
WITH got_tenth AS
SELECT last_name, salary
, NTILE (100) OVER (ORDER BY salary) AS hundredth
FROM hr.employees
SELECT last_name, salary
FROM got_tenth
WHERE hundredth > 100 - 12
ORDER BY salary DESC
;I won't clutter up this message by showing the results for every query; I'll just report the total number of rows. The query I posted earlier (for the top 10%) produced 10 rows of output; the query immediately above produces 12. That's starting to bother me. There are 107 rows in hr.employees. (They all have a salary; don't forget to deal with NULLs in general.) The top 10% should contain 107 * .1 = 10.7 rows. Of course, this has to be rounded to an integer, so it would have been a little better if the top 10% showed 11 rows (since 11 is closer to 10.7 than 10 is), but it's not a real big problem. Likewise, the top 12% should have 107 * .12 = 12.84 rows, so 13 rows of output might be better, but 12 rows isn't too bad.
Now say we want to simplify the condition "WHERE hundredth > 100 - 12". Instead of taking the last 12 buckets in ascending order, let's take the first 12 buckets in descending order:
WITH got_tenth AS
SELECT last_name, salary
, NTILE (100) OVER (ORDER BY salary DESC) AS hundredth
FROM hr.employees
SELECT last_name, salary
FROM got_tenth
WHERE hundredth <= 12
ORDER BY salary DESC
;The result set now contains 19 rows! Why? Because NTILE puts extra items (when there are extras) in the lower-numbered buckets. When there were 10 buckets, then buckets 1 trough 7 had 11 items each, and buckets 8 through 10 had 10 items. We were only dispolaying bucket #10, so we only saw 10 items. Now that there are 100 buckets, buckets 1 through 7 will have 2 items each, and buckets 8 through 100 will have 1 item each. When we numbered the buckets in ascending order, and took the last 12 buckets, we wound up with 12 * 1 = 12 rows, but when we numbered the buckets in descending order and took the first 12 buckets, we got (7 * 2) + (5 * 1) = 19 rows.
When you have R rows and B buckets, and R/B doesn't happen to be an integer, then NTILE will distribute the rows as equally as possible, but some rows will have 1 item more than others. When the ratio R/B is high, that might not be very significant, but when R/B gets close to 1, then you have situations like the one above, where the bigger buckets, although they have only 1 more item than the smaller buckets, are twice as big. Even worse is the situation where R/B is less than 1; then the last buckets will have 0 items.
So, as you noticed, NTILE isn't a good solution for all occasions. Here's a more accurate way, using the analytic ROW_NUMBER and COUNT functions:
WITH got_analytics AS
SELECT last_name, salary
, ROW_NUMBER () OVER (ORDER BY salary DESC) AS r_num
, COUNT (*) OVER () AS n_rows
FROM hr.employees
SELECT last_name, salary
FROM got_analytics
WHERE r_num / n_rows <= 12 / 100
ORDER BY salary DESC
;This produces 12 rows.
If you want 13 rows (because 107 * .12 = 12.84 is closer to 13), then you can change the main WHERE clause like this:
WITH got_analytics AS
SELECT last_name, salary
, ROW_NUMBER () OVER (ORDER BY salary DESC) AS r_num
, COUNT (*) OVER () AS n_rows
FROM hr.employees
SELECT last_name, salary
FROM got_analytics
WHERE r_num <= ROUND (n_rows * 12 / 100)
ORDER BY salary DESC
;
Maybe you are looking for
-
i have my select statement in my jsp like this.... <sql:query dataSource="${conn}" var="kur"> select ka_kod_sesi_semester sem, ka_kod_kursus kursus, BK_NAMA_KURSUS nama_kursus from akd.kursus_ambil, akd.bank_kursus, akd.pelajar where ka_no_matrik=pel
-
How can i add a donate now button to my iweb website
how can i add a donate now button to my iweb website
-
Crystal Reports Integration Issue
I am trying to integrate Crystal Reports 11 into Jdeveloper and I can get as far as to see the web report viewer with my report but I am also getting the following exception: NOTIFICATION J2EE JSP0008 Unable to dispatch JSP Page : java.lang.IllegalSt
-
ALE interface generation from BAPI_POEC_CREATE
Hi, I want to generate an ALE interface from BAPI_POEC_CREATE (object type BUS2201). FUNCTION BAPI_POEC_CREATE. *"*"Lokale Schnittstelle: *" IMPORTING *" VALUE(I_PO_HEADER) LIKE BAPI_PO_HEADER_C STRUCTURE *" BAPI_PO_HEADER_C *" VALUE
-
Nokia X6 *NEW* date bug.
This is a new possible bug which I've just spotted on my Nokia X6 16GB, which is slightly worse than the date incorrect bug described here: /t5/Xseries/X6-Date-incorrect/td-p/684385 Instead of the date on the phone reverting back by 24 hours, when I