1

I want to pull all rows except the last one in Oracle SQL

My database is like this

Prikey - Auto_increment
common - varchar
miles - int

So I want to sum all rows except the last row ordered by primary key grouped by common. That means for each distinct common, the miles will be summed (except for the last one)

EGN
  • 2,039
  • 4
  • 23
  • 37
  • check this http://stackoverflow.com/questions/470542/how-do-i-limit-the-number-of-rows-returned-by-an-oracle-query-after-ordering – Yogesh Jul 02 '13 at 13:55

3 Answers3

5

Note: the question was changed after this answer was posted. The first two queries work for the original question. The last query (in the addendum) works for the updated question.

This should do the trick, though it will be a bit slow for larger tables:

SELECT prikey, authnum FROM myTable
WHERE prikey <> (SELECT MAX(prikey) FROM myTable)
ORDER BY prikey

This query is longer but for a large table it should faster. I'll leave it to you to decide:

SELECT * FROM (
  SELECT
    prikey,
    authnum,
    ROW_NUMBER() OVER (ORDER BY prikey DESC) AS RowRank
  FROM myTable)
WHERE RowRank <> 1
ORDER BY prikey

Addendum There was an update to the question; here's the updated answer.

SELECT
  common,
  SUM(miles)
FROM (
  SELECT
    common,
    miles,
    ROW_NUMBER() OVER (PARTITION BY common ORDER BY prikey DESC) AS RowRank
  FROM myTable
)
WHERE RowRank <> 1
GROUP BY common
Ed Gibbs
  • 24,349
  • 2
  • 40
  • 62
  • sorry to come back again, but if I want to group by another field. please see the revised question – EGN Jul 02 '13 at 15:38
  • @DownMasters.com: Change `OVER (ORDER BY ...` to `OVER (PARTITION BY common ORDER BY ...` in the second query. –  Jul 02 '13 at 15:47
  • @DownMasters.com - please see the addendum to my answer. I'm pretty sure it answers your revised question. Let me know if you have any questions/problems. – Ed Gibbs Jul 02 '13 at 16:10
0

Looks like I am a little too late but here is my contribution, similar to Ed Gibbs' first solution but instead of calculating the max id for each value in the table and then comparing I get it once using an inline view.

SELECT d1.prikey,
  d1.authnum 
FROM myTable d1,
  (SELECT MAX(prikey) prikey myTable FROM myTable) d2
WHERE d1.prikey != d2.prikey

At least I think this is more efficient if you want to go without the use of Analytics.

Tar Patel
  • 428
  • 1
  • 6
  • 14
0

query to retrieve all the records in the table except first row and last row

select * from table_name 
where primary_id_column not in 
(
  select top 1 * from table_name order by primary_id_column asc
) 
and
primary_id_column not in 
(
  select top 1 * from table_name order by primary_id_column desc
)
Nilesh Gajare
  • 5,841
  • 2
  • 34
  • 62
mega
  • 1
  • 1