Simple max() sql query
Dear SQL Experts
i have data like below
id rate date
1 10 03-JAN-2010
1 20 02-JAN-2010
1 30 01-JAN-2010
2 10 01-JAN-2010
2 20 02-JAN-2010
2 30 10-JAN-2010
3 40 01-JAN-2010
3 50 15-JAN-2010
3 60 03-JAN-2010
I want to get the id wise last date's rate. like below
id rate date
1 10 03-JAN-2010 (As 3rd Jan is the max date)
2 30 10-JAN-2010 (As 10th Jan is the max date)
3 50 15-JAN-2010 (As 15th Jan is the max date)
You can use the following to avoid the subquery:
SQL> WITH DATA AS(
2 select 1 ID1,10 RATE,to_date('03 jan 2010','DD MON YYYY')DATE1 from dual UNION ALL
3 select 1 ID1,20 RATE,to_date('02 jan 2010','DD MON YYYY')DATE1 from dual UNION ALL
4 select 1 ID1,30 RATE,to_date('01 jan 2010','DD MON YYYY')DATE1 from dual UNION ALL
5 select 2 ID1,10 RATE,to_date('01 jan 2010','DD MON YYYY')DATE1 from dual UNION ALL
6 select 2 ID1,20 RATE,to_date('02 jan 2010','DD MON YYYY')DATE1 from dual UNION ALL
7 select 2 ID1,30 RATE,to_date('10 jan 2010','DD MON YYYY')DATE1 from dual UNION ALL
8 select 3 ID1,40 RATE,to_date('01 jan 2010','DD MON YYYY')DATE1 from dual UNION ALL
9 select 3 ID1,50 RATE,to_date('15 jan 2010','DD MON YYYY')DATE1 from dual UNION ALL
10 select 3 ID1,60 RATE,to_date('03 jan 2010','DD MON YYYY')DATE1 from dual )
11 Select id1, max(rate) keep(dense_rank last order by date1) rate, max(date1) date1
12 from data
13 group by id1;
ID1 RATE DATE1
1 10 03-JAN-10
2 30 10-JAN-10
3 50 15-JAN-10Max
Similar Messages
-
Hi,
This might be a simple question, I am new to Pl/SQL ,
I have a table which consists of two columns deal_id and freq.
for each deal_id there might be number of freq. The table something looks similar ltoo this,
deal_id freq
10 1.1
10 1.2
12 1.1
12 1.2
14 1.1
14 1.2
14 1.3
16 1.5
16 1.5
Now if a deal_id selected has freq 1.1 and 1.2 , it should display output has 'MA only'
if a deal_id selected has freq other than 1.1 and 1.2 , it should display 'Not MA'
else if it has like deal_id 14 should display . 'Both Ma and Non MA'
I wrote a query like this,
select
deal_id
, case
When Freq In (1.1 , 1.2) Then 'MA Only'
When Freq Not in (1.1 , 1.2) Then 'Non-MA Only'
Else 'Both Ma and Non-Ma'
End freq_dt
from sample_Table
where ia.deal_id= '14'
O/P i get is
deal_id freq_dt
14 MA only
14 MA only
14 Non MA only
But i should get O/p like
deal_id freq_dt
14 Both MA and Non Ma
Any help will be greatlt appreciated.
Thanks,
VinThanks Guys, for all your valuable suggestions.
These forums are helping me a lot.
Ok, back to the question, after going thru all the posts, i worked out on the query at work for a while and edited it something like this,
Select
case
when count(distinct freq_dt)>1 Then 'Both MA and Non-MA only'
Else <......>(pl refer below)
end status
from
(select
ia.deal_id
, case
when Freq In (851.0125, 851.5125, 852.0125, 852.5125, 853.0215) Then 'MA Only'
When Freq Not in (851.0125, 851.5125, 852.0125, 852.5125, 853.0215) Then 'Non-MA Only'
Else 'Both Ma and Non-Ma'
End freq_dt
from repl_site_freq ia
where ia.deal_id='65'
No worries, I know the query looks like useless, but I am working, I am new to Oracle,
and what i have done is performed a distinct count on the subquery.
Now if count >1 , i mean there is MA and Non-MA so it displays both MA and Non MA. Its working fine.
But now if count = 1, i mean if the whole subquery table has either MA or NOn-MA , then how can i catch that .
I mean if count =1, O/p shud be MA only if all are MA
and NON-MA if all are Non-MA.
Now I want to put this query in the else statement above
select st from
select
ia.deal_id
, case
when Freq In (851.0125, 851.5125, 852.0125, 852.5125, 853.0215) Then 'MA Only'
When Freq Not in (851.0125, 851.5125, 852.0125, 852.5125, 853.0215) Then 'Non-MA Only'
Else 'Both Ma and Non-Ma'
End st
from repl_site_freq ia
where ia.deal_id='32434'
A where rownum < 2
since this subquery just returns count=1, and i want to display the first item in first row of first column which can be either MA or NOn-MA
when i put the above quesry in else, it returns me some error, like groupby missing.
ANy help will be greatly appreciated.
Thanks,
Vin -
I am using SQL 2008. I have following table.
HostName
Timestamp
ErrorType
Server 1
2014-03-11 00:10:39.387
N/W Error
Server 2
2014-03-11 01:10:40.387
DB Error
Server 1
2014-03-11 00:20:39.387
N/W Error
Server 2
2014-03-11 02:10:40.387
N/W Error
Server 2
2014-03-11 02:00:39.387
N/W Error
Server 1
2014-03-11 03:30:39.387
N/W Error
Server 1
2014-03-11 03:45:39.387
N/W Error
Server 1
2014-03-12 13:45:39.387
N/W Error
Server 2
2014-03-12 14:45:39.387
DB Error
I would like to get how many errors occur per hour per server in a particular day. . So basically I will just pass date (such as 2014-03-11) in my query and it will be below report.
But I am not sure how to get it. Any help would be appreciated
HostName
NumberofError
Time
Errortype
Server 1
2
12 AM
N/W Error
Server 2
1
1 AM
DB Error
Server 2
2
2 AM
N/W Error
Server 1
2
3 AM
N/W Error
ThanksUse a table of time slots set to one more decimal second of precision than your data. You can now use temporal math to add it to a DATE to TIME(1) get a full DATETIME2(0). Here is the basic skeleton.
CREATE TABLE Timeslots
(slot_start_time TIME(1) NOT NULL PRIMARY KEY,
slot_end_time TIME(1) NOT NULL,
CHECK (start_time < end_time));
INSERT INTO Timeslots --15 min intervals
VALUES ('00:00:00.0', '00:14:59.9'),
('00:15:00.0', '00:29:59.9'),
('00:30:00.0', '00:44:59.9'),
('00:45:00.0', '01:00:59.9'),
('23:45:00.0', '23:59:59.9');
Here is the basic query for rounding down to a time slot.
SELECT CAST (@in_timestamp AS DATE), T.start_time
FROM Timeslots AS T
WHERE CAST (@in_timestamp AS TIME)
BETWEEN T.slot_start_time
AND T.slot_end_time;
Also, please stop using AM/PM and learn ANSI/ISO Standards.
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
List the branch number and names of shops which do not have any books written by Pratt in stock. Order the list by branch number.
how can I code this? if that statement was positive, i would say something like "where ..... author_last IN ('Pratt')"
But in this case, how can I do it? i don't think there's a command like "OUT" in SQL :)Hi,
If you how how to find the shops that DO have such books, then you're off to a good start!
Make a NOT EXISTS or NOT IN sub-query.
For example, in the scott.dept table, if you wanted to find all the departments that do not have any salesmen working in them (as found in the scott.emp table):
SELECT *
FROM scott.dept
WHERE deptno NOT IN ( SELECT deptno
FROM scott.emp
WHERE job = 'SALESMAN'
;"NOT IN" is sort of like "OUT". -
New user here and I haven't been able to find an answer to this. My table looks like
Name Code Date Issued Date Returned
Smith 22 10/05/05 10/10/05
Smith 3 10/05/05 10/06/05
Smith 102 10/10/05 10/12/05
Jones 1 10/10/05 10/11/05
Code is unique. I want a report for each user that looks like
Smith 3 10/05/05 10/10/05
22 10/05/05 10/06/05
102 10/10/05 10/12/05
Where the column "Name" does not repeat the value. I have tried various combinations of order by but can't get "name" to stop repeating, and have searched the FAQs and docs but can't find how to do this...I'm sure it's something simple I'm not seeing...thanks in advancecreate table mytable (
name varchar2(20)
, code number
, date_issued date
, date_returned date)
insert into mytable values ('Smith', 22, to_date('10/05/05','MM/DD/YY'), to_date('10/10/05','MM/DD/YY'))
insert into mytable values ('Smith', 3, to_date('10/05/05','MM/DD/YY'), to_date('10/06/05','MM/DD/YY'))
insert into mytable values ('Smith', 102, to_date('10/10/05','MM/DD/YY'), to_date('10/12/05','MM/DD/YY'))
insert into mytable values ('Jones', 1, to_date('10/10/05','MM/DD/YY'), to_date('10/11/05','MM/DD/YY'))
select decode(grp_rn, 1, name, null) name
, code
, date_issued
, date_returned
from ( select m.*
, row_number() over (partition by m.name order by m.name, m.code) grp_rn
from mytable m
NAME CODE DATE_ISSUED DATE_RETURNED
Jones 1 10/10/2005 10/11/2005
Smith 3 10/5/2005 10/6/2005
22 10/5/2005 10/10/2005
102 10/10/2005 10/12/2005Message was edited by:
splazm -
Pl help with simple pl/sql quey
Hi ,
I am getting stuck with this simple pl/sql query , can anyone pl help me with this.
This is the query i have,
select ia.deal_id, actual_clear_dt
from inc_site_freq isf
join INC_ASSET ia on isf.inc_asset_id = ia.inc_asset_id
and freq in (866.0125, 866.5125, 867.0125, 867.5125, 868.0125)
and deal_id=21363
the above query displays data of about 10 rows which may or may not have combination of null and dates for actua_clear_dt.
if its a combination of null and dates then all the actual_clear_dt should be null
if it has only dates should display all dates
Please help. Thanks.Vin wrote:
Hi ,
I am getting stuck with this simple pl/sql query , can anyone pl help me with this.
This is the query i have,
select ia.deal_id, actual_clear_dt
from inc_site_freq isf
join INC_ASSET ia on isf.inc_asset_id = ia.inc_asset_id
and freq in (866.0125, 866.5125, 867.0125, 867.5125, 868.0125)
and deal_id=21363
the above query displays data of about 10 rows which may or may not have combination of null and dates for actua_clear_dt.
if its a combination of null and dates then all the actual_clear_dt should be null
if it has only dates should display all dates
Please help. Thanks.A little indention/formatting would help you see and comprehend it better, and including the { code } tags when posting here would help US see and comprehend it better:
select
ia.deal_id,
actual_clear_dt
from
inc_site_freq isf
join INC_ASSET ia
on isf.inc_asset_id = ia.inc_asset_id
and freq in (866.0125,
866.5125,
867.0125,
867.5125,
868.0125)
and deal_id=21363 -
Simpler reprsentation to SQL Query is needed
Hi all,
I have this SQL Query working goon on the Database but have some errors with Form developer so can anybody simplify it?
SELECT *
FROM (SELECT COUNT (returned_goods.ID) AS "Max Occurence", products.Name
FROM Returned_Goods
JOIN Products
ON returned_goods.productId = products.Id
GROUP BY returned_goods.productId, products.Name
ORDER BY COUNT (returned_goods.ID) DESC)
WHERE ROWNUM = 1;btw, the error encounter me in Forms appears here if anybody can help: [SQL Code not working in Forms Developer without Functions|http://forums.oracle.com/forums/thread.jspa?threadID=842122&tstart=0]
Thanks in advance :)The simpler SQL Staement is
SELECT *
FROM (SELECT COUNT (returned_goods.ID) AS "Max Occurence", products.Name
FROM returned_goods, products
WHERE
Returned_Goods.ProductId = Products.id
GROUP BY returned_goods.productId, products.Name
ORDER BY COUNT (returned_goods.ID) DESC)
WHERE ROWNUM = 1; -
SQL Query to retrieve the All records based on the Max Dates.
Hello all,
I am trying to retrieve the newest record based on the date field ( nextDate ).
Currently there are only 4 records in the MC_Maintenance table and two in the Machine table.
Machine table
MC_id EquipID
1 0227
MC_id EquipID
2 0228
MC_Maintenance table
Maint_id MC_id Next_maint
1 2 08/25/2010
2 2 07/01/2010
3 1 06/11/2010
4 1 07/11/2010
What I am trying to accomplish is,
list the two machines from the Machine table with the MAX(Next_maint) controlling the MC_Maintenance output list
These are the records that I would like to Display.
Maint_id MC_id Next_maint
1 2 08/25/2010
4 1 07/11/2010
Below is the SQL Query
SELECT
MC.MC_ID as ID,
MC.complete_Date as completed,
MC.next_maint as nextDate,
MC.maint_notes as Notes,
MC.facility as Facility,
M.EquipId,
M.name as name,
M.SerialNumber as SN,
M.dept as dept,
M.Freq as freq
From MC_Maintenance MC, Machine M
where MC.MC_ID = M.MC_ID
' USING MAX(nextDate )
Any ideas would help.
TJI would have thought that was a simple group by problem?
SELECT M.EquipID, MC.MC_ID, Max(MC.next_maint)
FROM MC_Maintenance MC INNER JOIN Machine M ON MC.MC_ID = M.MC_ID
GROUP BY M.EquipID, MC.MC_ID -
How to get cm:search to use the max attribute when creating the SQL query?
When we use the max attribute in the cm:search tag, it does not seem to honor the max attribute when creating the SQL query. However, the result returned from the tag is limited to the number specified by the max attribute. Then the tag seems to work as intended, but the performance will be sub optimal when the SQL query returns unnecessary rows to the application.
We use the cm:search tag to list the latest news (ordered by date), and with the current implementation we have to expect a decrease in performance over time as more news is published. But we can’t live with that. We need to do the constraint in the SQL query, not in the application.
The sortBy attribute of cm:search is translated to “order by” in the SQL query, as expected.
Is it possible to get cm:search to generate the SQL query with an addition of “where rownum <= maxRows”?Hi Erik,
The behavior of a repository in regards to the search tag's max results parameter is dependent on the underlying repository's implementation. That said, the OOTB repository in WLP does augment the generated SQL to limit the number of rows returned from the database. This is done in the parsing logic. This behavior may differ with other repository implementations.
-Ryan -
SQL query problem - select max (case... aggregate function)
Hi,
I have a problem with below sql query, it gives me problem/error message 'ORA-00937: not a single-group group function', why?
select sag.afdeling, sag.sagsnr, to_char(sag.start_dato, 'yyyy-mm-dd'), sag.stat, BOGF_TRANS.TRANSTYPE,
max (case when BOGF_TRANS.TRANSTYPE = 'K' then sum(bogf_trans.belobdkk) end) + -- as "TRANSTYPE K",
max (case when BOGF_TRANS.TRANSTYPE = 'D' then sum(bogf_trans.belobdkk) end) as "TRANSTYPE K & D",
max (case when BOGF_TRANS.TRANSTYPE = 'S' then sum(bogf_trans.belobdkk) end) as "SUM TRANSTYPE S"
from sag
join bogf_trans on sag.selskab = bogf_trans.selskab and sag.sagsnr = bogf_trans.sagsnr and sag.afdeling = bogf_trans.afdeling
where SAG.SELSKAB=37 and SAG.AFDELING = 'SUS' AND SAG.SAGSNR = 10876
group by sag.afdeling, sag.sagsnr, sag.start_dato, sag.stat, BOGF_TRANS.TRANSTYPE
If I exclude (columns) as below it give me correct summations (max (case... sum(...)) but then I miss some important info that I need
select
max (case when BOGF_TRANS.TRANSTYPE = 'K' then sum(bogf_trans.belobdkk) end) + -- as "TRANSTYPE K",
max (case when BOGF_TRANS.TRANSTYPE = 'D' then sum(bogf_trans.belobdkk) end) as "TRANSTYPE K & D",
max (case when BOGF_TRANS.TRANSTYPE = 'S' then sum(bogf_trans.belobdkk) end) as "SUM TRANSTYPE S"
from sag
join bogf_trans on sag.selskab = bogf_trans.selskab and sag.sagsnr = bogf_trans.sagsnr and sag.afdeling = bogf_trans.afdeling
where SAG.SELSKAB=37 and SAG.AFDELING = 'SUS' AND SAG.SAGSNR = 10876
group by sag.afdeling, sag.sagsnr, sag.start_dato, sag.stat, BOGF_TRANS.TRANSTYPE
Any ideas?Moved to more sutable forum, sorry.
-
Simple SQL query SQL developer takes it, The wizzard of XE does not
Hello everybody
I wrote this simple query which SQL developer runs fine, but when I try to launch a Report based on this sql query it tells me invalid sql statement. That is true, it may be invalid because this IF clause in there..but SQL developer seems to be very tolerant or understands more...
the reason I wrote that is because obviously if there are no bosses, ie = 0 then i would get an error when dividing it by 0, so I put that 0 just to select the good ones
if count (bosses) >0
select company, postcode,
sum( bosses/staff)
from evaluation
group by company, postcode
Thank you very much
Alvarooh yes (blushed in shame as how dumb i looked like) i knew about the denominator 0 and infinite as as result i just didnt notice my zero was on the numerator :(
however, i run the query and i got this message in sql developer
Error starting at line 1 in command:
select company, postcode,
case when staff != 0 then sum( bosses/staff) end
from evaluation
group by company, postcode
Error at Command Line:2 Column:10
Error report:
SQL Error: ORA-00979: not a GROUP BY expression
00979. 00000 - "not a GROUP BY expression"
*Cause:
*Action: -
I just wanted to note this on the forum..
I'm using Apex 3.0.1.00.08
My DEV environment has just been upgraded from 10g version 10.2.0.2.0 to 10.2.0.4.0.
I created the following process to select some values into some items on my Form page.
select MAX(STAT_YEAR+1)
, pcd.pct_id
, pcd.stat_type_id
, pcd.stat_period_type_id
, pcd.measurement_id
into :P11_STAT_YEAR
, :P11_PCT_ID
, :P11_STAT_TYPE_ID
, :P11_STAT_PERIOD_TYPE_ID
, :P11_MEASUREMENT_ID
from plant_commodity_data pcd
, stat_type stt
where pcd.STAT_TYPE_ID = stt.STAT_TYPE_ID
and pcd.pct_id = :P0_PCT_ID
and stt.stat_type = 'PRD'
group by pcd.pct_id
, pcd.stat_type_id
, pcd.stat_period_type_id
, pcd.measurement_id;The process should run conditionally if there was at least one row to select...
So I copied the SQL into the Process condition, removed the "into" section and set the condition type to be "Exists (SQL query retruns at least one row) ...
select MAX(STAT_YEAR+1)
, pcd.pct_id
, pcd.stat_type_id
, pcd.stat_period_type_id
, pcd.measurement_id
from plant_commodity_data pcd
, stat_type stt
where pcd.STAT_TYPE_ID = stt.STAT_TYPE_ID
and pcd.pct_id = :P0_PCT_ID
and stt.stat_type = 'PRD'
group by pcd.pct_id
, pcd.stat_type_id
, pcd.stat_period_type_id
, pcd.measurement_id;This worked perfectly until the DEV environment was upgraded from 10g version 10.2.0.2.0 to 10.2.0.4.0.
The condition would fire even if there were no rows returning.
I pasted the condition code into SQL Developer connected to the DEV (10.2.0.4.0) environment and it returned no rows.
To solve the problem, I removed the MAX.
You can test this using this code if you have access to the two versions... select MAX(1)
, sysdate
, 'Gus'
from dual
where 1 = 2
group by sysdate, 2Now I know the MAX isn't required in the condition as I'm just trying to find out if any rows exist, but it was there as I copied the code in... I was just wondering why this happened between 10.2.0.2.0 and 10.2.0.4.0?
Gus..Hi Gus,
try to execute
select count(*) from dual where exists (select MAX(1)
, sysdate
, 'Gus'
from dual
where 1 = 2
group by sysdate, 2)in SQL Developer. The above statement is generated by APEX for an "Exists (SQL query retruns at least one row)". Can't test it, because I don't have a 10.2.0.4.0 at hand.
Does SQL Developer now show the same behavior?
Patrick
My APEX Blog: http://www.inside-oracle-apex.com
The APEX Builder Plugin: http://builderplugin.oracleapex.info/
The ApexLib Framework: http://apexlib.sourceforge.net/ -
Simple SQL Query and Parameters and LOV
Newbie and trying to work thru building a simple sql query with a single table query and use a parameter and lov.
Can anyone point me to an example.
simple query:
select cust_id, name_desc, name_add1, name_add2, name_city
from customer_table
where cust_id = :cust_parm
This works in straight sql and in the query builder by prompting for the customer ID. When building a parameter using LOV or search, it doesn't seem to detect the variable.
Thanks..
DDIf you are using version 11g, then as soon as you save the query in the data model, it should notice the parameter and ask if you want to add the parameter to the data model. What version of BIP are you using?
What happens if you exclude the parameter from the query and simply hard-code the criteria? Can you generate XML data?
From your wording, it sounds like you're trying to create a parameter from the LOV dialog. LOVs and parameters are totally distinct. After each are created separately, then you configure the parameter to use the LOV. -
Simple SQL query statement is needed
I need a simple SQL query to fetch records which is existed in all the departments.
for example: i want to list the employees which are existed in each and every department.. not sure how should i get those.. will anyone help me please.. thanks in advanceI think it would be wise to go to the following training:
Oracle Database <version> : Introduction to SQL
You will get the information you are looking for in five days. You can go find a tutorial on ANSI SQL, as advised by this board for free, to fix your immediate problem with a simple query. But, I personally recommend a more formal class specific to Oracle, as you will also get information about PL/SQL, and you get the benefit with working with other DBA/programmers when you are learning. This will solve your immediate issue, and any future issues with the language.
You can find it in the Education section of the Oracle website. -
Is there max lenght of sql query
hello
i want to ask is there max lenght (count of chars) of sql query ?In the old days it was 64K however according to Oracle, "The limit on how long a SQL statement can be depends on many factors, including database configuration, disk space, and memory ."
Ref (Oracle Support Document): Database Limits #336186.1
You may wish to check the Oracle version# Reference manual for your version of Oracle. There may be a note there.
HTH -- Mark D Powell --
Edited by: Mark D Powell on Oct 14, 2010 1:28 PM
Maybe you are looking for
-
Hi all, I m using look up through JCO and calling a RFC on backend R/3 for the particular validation.I m using UDF for that.In the UDF i have specified imports as:- imports :-java.util.;java.lang.obj.;com.sap.aii.mapping.lookup.;com.sap.mw.jco.;java.
-
Whilst performing a zero/erase install on my Powerbook G4 Firewire (aluminium) with an OSX Tiger install disk (Tiger was the OSX i had erased), I had to force quite the installer as it appeared to be stuck on the Chinese script install section. I cra
-
Changed apple id. How do I change the iCloud settings on my iPhone?
Since I changed my apple ID, my phone no longer syncs with iCloud. It still shows my old apple ID. I tried deleting the iCloud account from my phone, but that deletes all the appointments from my calander! I can then add my new apple I'd in iCloud
-
Magic Trackpad...Jerky Zoom in Safari 5.0.1
I was hoping that the two finger zoom would work well in Safari 5. Unfortunately it zooms in a jerky step fashion.....Unlike Photoshop CS4 where it is silky smooth. So why can't Apple implement a smooth two finger zoom in two of it's otherwise really
-
Hi Team, I have created a custom namespace(TEST), by using this namespace i have created my own WDA applications, but when i try to move this applications to QA system, namespace got transfered and applications also available in QA system but i am no