top 10 rows in oracle [duplicate] - sql

This question already has answers here:
Oracle SQL - How to Retrieve highest 5 values of a column [duplicate]
(5 answers)
Oracle SELECT TOP 10 records [duplicate]
(6 answers)
Closed 6 years ago.
i have 2 tables .
abc(CID(pk), cname,)
order(order_id(pk), CID(fk), number_of_rentals)
i want to fetch top 10 customers based on number of rentals.
SELECT cid, sum(no_rentals) as sum
FROM orders
group by cid, no_rentals
order by no_rentals desc;
how can i use rownum function in above query to fetch the desired output

Just wrap your query in:
SELECT * FROM ( your_query ) WHERE ROWNUM <= 10;
However, your query does not look like it is going to do what you intend as the GROUP BY no_renalts will mean that each distinct no_rentals value will be in its own group and you will not sum the values for each customer so you probably don't want to include it in the GROUP BY. Also, if you want to order by the total number of rentals then you want to ORDER BY SUM( no_rentals ) (or by its alias) like this:
SELECT cid,
SUM(no_rentals) as total_no_rentals
FROM orders
GROUP BY cid
ORDER BY total_no_rentals DESC;
Then you can apply the row limit like this:
SELECT *
FROM (
SELECT cid,
SUM(no_rentals) as total_no_rentals
FROM orders
GROUP BY cid
ORDER BY total_no_rentals DESC
)
WHERE ROWNUM <= 10;

Related

Select Attribiute B where Attribiute A is maximal after groupby in SQL [duplicate]

This question already has answers here:
how to select max(column) and a column in the same request teradata
(3 answers)
Closed 8 months ago.
Given the following table:
ID
Price
Date
1
34
a
1
42
b
2
34
a
I would like to have one row per ID where the price was maximal
ID
Price
Date
1
42
b
2
34
a
Trying to groupby ID and selecting ID, Date, MAX(Price) results in the error GROUP BY clause with non aggregate functions
You can use row_number.
SELECT *
FROM
your_table_name
QUALIFY ROW_NUMBER() OVER (partition by id order by price desc) = 1;
The Qualify clause is used to filter the results of ordered analytical
function according to user‑specified search conditions. We can use
this conditional clause in the SELECT statement to get the particular
order values.

Why alias in SQL is not remember a subquery as a new table? [duplicate]

This question already has answers here:
Create a view with ORDER BY clause
(10 answers)
Order BY is not supported in view in sql server
(3 answers)
How to sort within a sql view
(4 answers)
Order by error in create view in SQL Server
(2 answers)
Does order by in view guarantee order of select?
(3 answers)
Closed 9 months ago.
I have a table SALE with 2 columns ID and Sales.
I have code like this:
SELECT TOP 100 PERCENT ID, Sales
FROM SALE
WHERE ProductID = 'IDN001'
ORDER BY Sales DESC;
And the result is here:
But if I put all the code above inside the SELECT * FROM, it shows me the original TABLE (before ordering):
SELECT *
FROM
(SELECT TOP 100 PERCENT ID, Sales
FROM SALE
WHERE ProductID = 'IDN001'
ORDER BY Sales DESC) AS NewQuery;
The new result is here:
How can I fix this?
Thank you.
The ordering of a subquery does not "stick" in a SQL Server query. You need to add an explicit ORDER BY clause to the outer query to get the sorting behavior you want:
SELECT *
FROM
(
SELECT TOP 100 PERCENT ID, Sales
FROM SALE
WHERE ProductID = 'IDN001'
ORDER BY Sales DESC
) AS NewQuerry
ORDER BY Sales DESC;

how to select only max(id) if you need less columns in group by [duplicate]

This question already has answers here:
Fetch the rows which have the Max value for a column for each distinct value of another column
(35 answers)
Select First Row of Every Group in sql [duplicate]
(2 answers)
Return row with the max value of one column per group [duplicate]
(3 answers)
Get value based on max of a different column grouped by another column [duplicate]
(1 answer)
Closed 3 years ago.
The thing is that i could have values like
ID STREET_ID HOUSENUMBER POSTCODE
10000000 20512120 22 04114
11000000 20512120 22 04074
problem is that POSTCODE have to be in select, but i need distinct STREET_ID + HOUSENUMBER with MAX id,
by example i just want to show 11000000,20512120,22,04074 out of 2 records because of MAX(h.ID).
this is my code
SELECT DISTINCT
MAX(h.ID),
h.street_id,
h.houseNumber,
h.postindex AS postCode
FROM house h
WHERE
h.postindex IS NOT NULL AND
h.STREET_ID IS NOT NULL
GROUP BY
h.street_id,
h.houseNumber
ORDER BY
STREET_ID,
CAST(REGEXP_REPLACE(REGEXP_REPLACE(h.houseNumber, '(\-|\/)(.*)'), '\D+') AS NUMBER),
h.houseNumber
i have an error " ORA-00979: not a GROUP BY expression " and i understand it, because POSTCODE is not in GROUP BY, how to deal with that?
Your requirement is a good candidate for ROW_NUMBER:
WITH cte AS (
SELECT h.*,
ROW_NUMBER() OVER (PARTITION BY h.STREET_ID, h.HOUSENUMBER ORDER BY h.ID DESC) rn
FROM house h
)
SELECT ID, STREET_ID, HOUSENUMBER, POSTCODE
FROM cte
WHERE rn = 1;
An index on (STREET_ID, HOUSENUMBER, ID) might speed up the above query, because it would let Oracle quickly find the max ID record for each street/house number.
You can do it with subquery and exists:
SELECT *
FROM house h
WHERE NOT EXISTS (SELECT 1 FROM house h2
WHERE h2.street_id = h.street_id
AND h2.houseNumber = h.houseNumber
AND h2.id > h.id)
Don't aggregate. Instead, you can filter with a correlated subquery:
select h.*
from house h
where id = (
select max(h1.id)
from house h1
where h1.street_number = h.street_number and h1.house_number = h.house_number
)
I would expect this solution to be as efficient as it gets, especially with an index on (street_number, house_number, id).
select distinct id,street_id,house_no,postal_code from house where id in (
SELECT MAX(id) from house group by street_id,house_no)

SQL Selecting dates with maximum sale for each department [duplicate]

This question already has answers here:
Fetch the rows which have the Max value for a column for each distinct value of another column
(35 answers)
Oracle SQL query: Retrieve latest values per group based on time [duplicate]
(2 answers)
Get value based on max of a different column grouped by another column [duplicate]
(1 answer)
SQL: getting the max value of one column and the corresponding other columns [duplicate]
(2 answers)
Closed 3 years ago.
I am troubled with writing a tricky query.
I have the following table:
For each department I want to print date with largest profit;
I tried coming up with such a query myself:
Select DISTINCT(Name), Date_sale, MAX(A) as B FROM (SELECT
Departments.Name, SALES.Date_sale, SUM(GOODS.Price * SALES.Quantity)
AS A FROM DEPARTMENTS, GOODS, SALES
WHERE DEPARTMENTS.Dept_id = GOODS.Dept_id AND GOODS.Good_id =
SALES.Good_id GROUP BY DEPARTMENTs.Name, SALES.Date_sale)
GROUP BY Name, Date_sale;
But the problem it that departments are printed several times because I groupped by both name and date.
How should I fix it?
You can try below way-
with cte as
(
SELECT
Departments.Name, SALES.Date_sale, SUM(GOODS.Price * SALES.Quantity)
AS profit FROM DEPARTMENTS inner join GOODS on DEPARTMENTS.Dept_id = GOODS.Dept_id
inner join SALES on GOODS.Good_id = SALES.Good_id
GROUP BY DEPARTMENTs.Name, SALES.Date_sale
)A
select * from cte a
where profit =
(select max(profit) from cte b on a.department=b.department)
OR you can use row_number()
select * from
(
select *, row_number() over(partition by department oder by profit desc) as rn
from cte
)A where rn=1
You can write it using ROW_NUMBER which will give a number to each date's total count grouped by the department as following and then you can take the highest sale date using rn = 1
SELECT NAME, DATE_SALE, A
FROM
(
SELECT
DEPARTMENTS.NAME, SALES.DATE_SALE,
ROW_NUMBER() OVER(
PARTITION BY DEPARTMENTS.NAME
ORDER BY SUM(GOODS.PRICE * SALES.QUANTITY) DESC NULLS LAST
) AS RN,
SUM(GOODS.PRICE * SALES.QUANTITY) AS A
FROM DEPARTMENTS
JOIN GOODS ON ( DEPARTMENTS.DEPT_ID = GOODS.DEPT_ID )
JOIN SALES ON ( GOODS.GOOD_ID = SALES.GOOD_ID )
GROUP BY DEPARTMENTS.NAME,
SALES.DATE_SALE
)
WHERE RN = 1;
Important, Use the standard ANSI-joins.
Cheers!!
i would use join-s here as it is needed to pull info from 2 tables linked via the third table.
Something like this (but I have not tested this query, just suggesting an approach):
Select department.name as dept, MAX(sales.quantity) as max_sales, sales.date_sale
from goods
Left outer join departments on departments.dept_id = goods.dept_id
Left outer join sales on sales.good_id = goods.good_id
Group by dept

SQL Query - Finding rows for a highest index number [duplicate]

This question already has answers here:
Fetch the rows which have the Max value for a column for each distinct value of another column
(35 answers)
Oracle SQL query: Retrieve latest values per group based on time [duplicate]
(2 answers)
Get top results for each group (in Oracle)
(5 answers)
GROUP BY with MAX(DATE) [duplicate]
(6 answers)
Return row with the max value of one column per group [duplicate]
(3 answers)
Closed 5 years ago.
I am struggling to find a correct way to query the following scenario. Consider the below table as example, where I want the row with index_no 124 for that dvpc and pid value of the columns. Please suggest.
Index_No dvpc pid rate
123 123 30 0.01
124 123 30 0.02
Use ROW_NUMBER to assign a ranking on Index_No for each value of dvpc and pid, then filter to the ones with the highest rank.
SELECT Index_No, dvpc, pid, rate
FROM (SELECT Index_No, dvpc, pid, rate,
ROW_NUMBER() OVER (PARTITION BY dvpc, pid ORDER BY Index_no DESC) rn
FROM your_table) yt
WHERE rn = 1;
You could use max() and GROUP BY.
For example:
select
dvpc,
pid,
max(index_no) as max_index
from
your_table
group by
dvpc,
pid
If you require the rate for that index, then something like this would work
select
t.*
from
your_table t
inner join
(
select
dvpc,
pid,
max(index_no) as max_index
from
your_table
group by
dvpc,
pid
) s
on t.index_no = s.max_index
Hope this helps