SQL query using MAX function
I am trying to only display the records where the 'date_entered' is the most recent date per case number.
SELECT distinct c.case_number, u.email,c.assigneddate_chart,
--m.date_entered,
max(m.date_entered)as last_date_entered,
trunc(sysdate)-trunc(c.assigneddate_chart)days_late,
trunc(sysdate)-trunc(m.date_entered)addl_days_late
from chart c, chart_user_roles u,comments m
where
(c.case_status IN ('Open','Pending')) and
c.case_number=m.case_number
group by c.case_number,
u.email,c.assigneddate_chart,m.date_enteredRight now, this is the output im am getting.
Output:
CASE_NUMBER------EMAIL---------ASSIGNEDDATE_CHART---LAST_DATE_ENTERED---DAYS_LATE--ADDL_DAYS_LATE
[email protected]----06-NOV-09-----------------31--------------------11
[email protected]----10-NOV-09-----------------31---------------------7
[email protected]----06-NOV-09-----------------31--------------------11
[email protected]----06-NOV-09-----------------31--------------------11
[email protected]----06-NOV-09-----------------31--------------------11
[email protected]----03-NOV-09-----------------34--------------------14
I am wanting to achieve this output:
Therefore, based on the data below, the only records that i am wanting to display are:
[email protected]----10-NOV-09-----------------31---------------------7
[email protected]----03-NOV-09-----------------34--------------------14
Thanks
Deanna
Is there a reason that you have a DISTINCT in your query? It always makes me nervous to see that where it's not clearly necessary because it frequently means that a developer is missing a join condition and is using the DISTINCT to mask that fact.
On to the meat of your question, though, is there a potential for ties? If so, how do you want to handle that-- do you want two rows for that case, do you want to break the tie using some other column, do you want to pick an arbitrary row? If you want to pick an arbitrary row
SELECT case_number, email, assignedDate_chart, last_date_entered, days_late, addl_days_late
FROM (
SELECT a.*, row_number() over (partition by case_number order by date_entered) rn
FROM (<<your query>>) a
WHERE rn = 1If you want to do something else, just adjust the analytic function and use RANK or add a tie-breaker to the ORDER BY.
Justin
Similar Messages
-
SQL Query - Using Lag function
Hi All,
I need to select the previous and next record, when the value of column is changed for each account.
My table structure is as follows:
Account_No number(10)
Payment_type number(5)
Installment_Type number(5)
Date_chage date
Sample record:
Account_No Payment_Type Installment_Type Date_change
70539 ** 1 ** 2 ** 01-OCT-83
70539 ** 1 ** 2 ** 03-FEB-01
70539 ** 1 ** 2 ** 26-APR-02
70539 ** 1 ** 1 ** 21-JUN-02
70539 ** 1 ** 2 ** 12-JUL-02
185562 ** 1 ** 2 ** 23-APR-02
185562 ** 2 ** 2 ** 10-MAY-02
In the above sample data, the value of instalment is changed on 21-jun-02 and 12-jul-02 for the account 70539. Also the value of Payment Type is changed on 23-apr-02 for the account 185562.
So, my output should be like this.
Account_No Payment_Type Installment_Type Date_change
70539 ** 1 ** 2 ** 26-APR-02
70539 ** 1 ** 1 ** 21-JUN-02
70539 ** 1 ** 2 ** 12-JUL-02
185562 ** 1 ** 2 ** 23-APR-02
185562 ** 2 ** 2 ** 10-MAY-02
I tried with lag function, but I couldnt succeed. Im using oracle 8.1.6 Version.
Can anyone help me to achieve this?
** To distinguish the value for each coulmn.
Thanks and regards,
Vijay R.With the information you have provided, I've come up with the following.
SELECT A.ACCOUNT_NO, A.PAYMENT_TYPE, A.INSTALLMENT_TYPE, A.DATE_CHANGE
FROM
(SELECT account_no, payment_type, installment_type, date_change,
LEAD( (payment_type), 1)
over (partition by account_no order by account_no, DATE_CHANGE) LEAD_PAY,
LEAD( (installment_type), 1)
over (partition by account_no order by account_no, DATE_CHANGE) LEAD_INST
from T_ACCNTS ) A
WHERE A.PAYMENT_TYPE <> NVL(A.LEAD_PAY,99)
OR A.INSTALLMENT_TYPE <> NVL(A.LEAD_INST,99)
ORDER BY 1, 4; -
SQL Query With analytical function
Hi
Below is the scenario which i am looking for in sql query using analytical functions
I/p
Col1
50
0
-150
-200
300
-100
-300
500
-100
O/p
Col1 col2
50 0
0 0
-150 -100
-200 -200
300 0
-100 0
-300 -100
500 400
-100 0Any help really appreciated
Thanks in advance
Edited by: unique on Aug 10, 2010 4:53 AM
Edited by: unique on Aug 10, 2010 4:55 AM
Edited by: unique on Aug 10, 2010 4:55 AMOh,In this case,There is OLAP solution ;-)
OLAP samples of my homepage http://www.geocities.jp/oraclesqlpuzzle/oracle-sql1-olap.html
with work(SK,Val) as(
select 1, 50 from dual union
select 2, 0 from dual union
select 3,-150 from dual union
select 4,-200 from dual union
select 5, 300 from dual union
select 6,-100 from dual union
select 7,-300 from dual union
select 8, 500 from dual union
select 9,-100 from dual)
select SK,Val,GID,
case when Val > 0
then greatest(0,sum(Val) over(partition by GID))
else Least(0,Val+greatest(0,sum(Val) over(partition by GID
order by SK rows between unbounded preceding
and 1 preceding)))
end as COL3
from (select SK,Val,
sum(greatest(0,sign(Val))) over(order by SK) as GID
from work)
order by SK;
SK VAL GID COL3
1 50 1 0
2 0 1 0
3 -150 1 -100
4 -200 1 -200
5 300 2 0
6 -100 2 0
7 -300 2 -100
8 500 3 400
9 -100 3 0 -
How to use MAX function in SSAS MDX Query
I want to run this Query with MAX Condition on LAST_DATA_UPDATE Column .
Hi Ashishsingh,
According to your description, you want to know how to use MAX function in SQL Server Analysis Services MDX Query, right? In this case, please refer to the link below which describe the syntax and sample of MDX function.
http://technet.microsoft.com/en-us/library/ms145601.aspx
http://www.mdxpert.com/Functions/MDXFunction.aspx?f=64
Hope this helps.
Regards,
Charlie Liao
TechNet Community Support -
Using max function in PL/SQL
VERY URGENT...
Am new to oracle...
I've written a package that display gif images in form of histogram/bar chart. using html,
I need to use max function to display values proportionately.
please help. i need to complete this assignment by 2/9/00 by 10.00 am at the latest. I've half written a function but I don't know if there's a simpler way fo doing this. html enabledFirst of all Thanks to all gentlemen who replied ..many thanks ...
Tried the ROW_NUMBER() option but still it is taking time...have given output for the query and tkprof results as well. Even when it doesn't fetch any record ( this is a valid cased because the input header id doesn't have any workflow request submitted & hence no entry in the wf_items table)..then also see the time it has taken.
Looked at the RANK & DENSE_RANK options which were suggested..but it is still taking time..
Any further suggestions or ideas as to how this could be resolved..
SELECT 'Y', 'Y', ITEM_KEY
FROM
( SELECT ITEM_KEY, ROW_NUMBER() OVER(ORDER BY BEGIN_DATE DESC) RN FROM
WF_ITEMS WHERE ITEM_TYPE = 'xxxxzzzz' AND ROOT_ACTIVITY = 'START_REQUESTS'
AND SUBSTR(ITEM_KEY,1,INSTR(ITEM_KEY,'-') - 1) = :B1
) T WHERE RN <= 1
call count cpu elapsed disk query current rows
Parse 0 0.00 0.00 0 0 0 0
Execute 1 0.00 1.57 0 0 0 0
Fetch 1 8700.00 544968.73 8180 8185 0 0
total 2 8700.00 544970.30 8180 8185 0 0
many thanks -
How to obtain the transformed SQL query using SEM_MATCH
Dear all,
Is it possible to get the transformed relational SQL query when using the SEM_MATCH prefix, by querying directly on the database. We are able to obtain the relational SQL query using Joseki/Jena, however this is not the way to go for us. We would like (if possible) to get it straight from the oracle database by logging or something.
Kind regards.
MaxHi Max,
Just to clarify. What SEM_MATCH prefix are you talking about?
A SEM_MATCH based query is indeed a SQL query as SEM_MATCH is a SQL table function. So if you don't want to go through Java APIs or web service endpoint, then running SEM_MATCH directly should give you what you need. Or maybe you just want to see the underlying generated (from SEM_MATCH) SQL query. If that is true, can you please tell us why?
Thanks,
Zhe Wu -
How can rewrite the Query using Analytical functions ?
Hi,
I have the SQL script as shown below ,
SELECT cd.cardid, cd.cardno,TT.TRANSACTIONTYPECODE,TT.TRANSACTIONTYPEDESC DESCRIPTION,
SUM (NVL (CASE tt.transactiontypecode
WHEN 'LOAD_ACH'
THEN th.transactionamount
END, 0)
) AS load_ach,
SUM
(NVL (CASE tt.transactiontypecode
WHEN 'FUND_TRANSFER_RECEIVED'
THEN th.transactionamount
END,
0
) AS Transfersin,
( SUM (NVL (CASE tt.transactiontypecode
WHEN 'FTRNS'
THEN th.transactionamount
END,
0
) +
SUM (NVL (CASE tt.transactiontypecode
WHEN 'SEND_MONEY'
THEN th.transactionamount
END, 0)
)) AS Transferout,
SUM (NVL (CASE tt.transactiontypecode
WHEN 'WITHDRAWAL_ACH'
THEN th.transactionamount
END, 0)
) AS withdrawal_ach,
SUM (NVL (CASE tt.transactiontypecode
WHEN 'WITHDRAWAL_CHECK'
THEN th.transactionamount
END, 0)
) AS withdrawal_check,
( SUM (NVL (CASE tt.transactiontypecode
WHEN 'WITHDRAWAL_CHECK_FEE'
THEN th.transactionamount
END,
0
) +
SUM (NVL (CASE tt.transactiontypecode
WHEN 'REJECTED_ACH_LOAD_FEE'
THEN th.transactionamount
END,
0
) +
SUM (NVL (CASE tt.transactiontypecode
WHEN 'WITHDRAWAL_ACH_REV'
THEN th.transactionamount
END,
0
) +
SUM (NVL (CASE tt.transactiontypecode
WHEN 'WITHDRAWAL_CHECK_REV'
THEN th.transactionamount
END,
0
) +
SUM
(NVL (CASE tt.transactiontypecode
WHEN 'WITHDRAWAL_CHECK_FEE_REV'
THEN th.transactionamount
END,
0
) +
SUM
(NVL (CASE tt.transactiontypecode
WHEN 'REJECTED_ACH_LOAD_FEE_REV'
THEN th.transactionamount
END,
0
) +
SUM (NVL (CASE tt.transactiontypecode
WHEN 'OVERDRAFT_FEE_REV'
THEN th.transactionamount
END, 0)
) +
SUM (NVL (CASE tt.transactiontypecode
WHEN 'STOP_CHECK_FEE_REV'
THEN th.transactionamount
END,
0
) +
SUM (NVL (CASE tt.transactiontypecode
WHEN 'LOAD_ACH_REV'
THEN th.transactionamount
END, 0)
) +
SUM (NVL (CASE tt.transactiontypecode
WHEN 'OVERDRAFT_FEE'
THEN th.transactionamount
END, 0)
) +
SUM (NVL (CASE tt.transactiontypecode
WHEN 'STOP_CHECK_FEE'
THEN th.transactionamount
END, 0)
)) AS Fee,
th.transactiondatetime
FROM carddetail cd,
transactionhistory th,
transactiontype tt,
(SELECT rmx_a.cardid, rmx_a.endingbalance prev_balance, rmx_a.NUMBEROFDAYS
FROM rmxactbalreport rmx_a,
(SELECT cardid, MAX (reportdate) reportdate
FROM rmxactbalreport
GROUP BY cardid) rmx_b
WHERE rmx_a.cardid = rmx_b.cardid AND rmx_a.reportdate = rmx_b.reportdate) a
WHERE th.transactiontypeid = tt.transactiontypeid
AND cd.cardid = th.cardid
AND cd.cardtype = 'P'
AND cd.cardid = a.cardid (+)
AND CD.CARDNO = '7116734387812758335'
--AND TT.TRANSACTIONTYPECODE = 'FUND_TRANSFER_RECEIVED'
GROUP BY cd.cardid, cd.cardno, numberofdays,th.transactiondatetime,tt.transactiontypecode,TT.TRANSACTIONTYPEDESC
Ouput of the above query is :
CARDID CARDNO TRANSACTIONTYPECODE DESCRIPTION LOAD_ACH TRANSFERSIN TRANSFEROUT WITHDRAWAL_ACH WITHDRAWAL_CHECK FEE TRANSACTIONDATETIME
6005 7116734387812758335 FUND_TRANSFER_RECEIVED Fund Transfer Received 0 3.75 0 0 0 0 21/09/2007 11:15:38 AM
6005 7116734387812758335 FUND_TRANSFER_RECEIVED Fund Transfer Received 0 272 0 0 0 0 05/10/2007 9:12:37 AM
6005 7116734387812758335 WITHDRAWAL_ACH Withdraw Funds via ACH 0 0 0 300 0 0 24/10/2007 3:43:54 PM
6005 7116734387812758335 SEND_MONEY Fund Transfer Sent 0 0 1 0 0 0 19/09/2007 1:17:48 PM
6005 7116734387812758335 FUND_TRANSFER_RECEIVED Fund Transfer Received 0 1 0 0 0 0 18/09/2007 7:25:23 PM
6005 7116734387812758335 LOAD_ACH Prepaid Deposit via ACH 300 0 0 0 0 0 02/10/2007 3:00:00 AM
I want the output like for Load_ACH there should be one record etc.,
Can any one help me , how can i rewrite the above query using analytical functions .,
SekharNot sure of your requirements but this mayhelp reduce your code;
<untested>
SUM (
CASE
WHEN tt.transactiontypecode IN
('WITHDRAWAL_CHECK_FEE', 'REJECTED_ACH_LOAD_FEE', 'WITHDRAWAL_ACH_REV', 'WITHDRAWAL_CHECK_REV',
'WITHDRAWAL_CHECK_FEE_REV', 'REJECTED_ACH_LOAD_FEE_REV', 'OVERDRAFT_FEE_REV','STOP_CHECK_FEE_REV',
'LOAD_ACH_REV', 'OVERDRAFT_FEE', 'STOP_CHECK_FEE')
THEN th.transactionamount
ELSE 0) feeAlso, you might want to edit your post and use [pre] and [/pre] tags around your code for formatting. -
What is the best way to Optimize a SQL query : call a function or do a join?
Hi, I want to know what is the best way to optimize a SQL query, call a function inside the SELECT statement or do a simple join?
Hi,
If you're even considering a join, then it will probably be faster. As Justin said, it depends on lots of factors.
A user-defined function is only necessary when you can't figure out how to do something in pure SQL, using joins and built-in functions.
You might choose to have a user-defined function even though you could get the same result with a join. That is, you realize that the function is slow, but you believe that the convenience of using a function is more important than better performance in that particular case. -
Oracle:how to use max() function in case expression
how to use max() function in case expression, Please explain with any example
Hope this helps and should be self explanatory
with t as
(select 1 col,100 col2 from dual union
select 2 ,100 from dual union
select 2 ,200 from dual union
select 3,100 from dual union
select 3,200 from dual )
select col, case when max(col2)=100 then 'with 100 range'
when max(col2)=200 then 'with 200 range' end from t group by col -
Max value without using max() function
Hi
Is there any way to get the max value from a table without using MAX() function
Thankswell if you think about it i'm sure you'll find a solution
what does max(field) means, it simply is the value of the field where no other value of the same field that is > than this value exists.
consider the following :
table TAB(
fld NUMBER(5));
translate the logic and you'll have
select a.fld from TAB a where NOT EXISTS(select b.fld from TAB b where b.fld>a.fld) and rownum=1;
of course there are better ways i'm sure, you'll just have to figure'em out. -
Set TIMEOUT on OCCI sql query using ?
Is there a way to set a timeout on a sql query using OCCI ?
OCCI does not provide an API to set timeouts on SQL Queries.
You can use the CREATE PROFILE command and assign resources at
a user level. The restrictions may be applied to memory/resources which
in turn would control the SQL execution time. Please check the
CREATE PROFILE command.
Rgds
Amogh -
How to find sql query using sqlid
Hi
I am not aware of that sqlid .DBA is saying a particular sqlid is making problem .how to find the particular sql query using sql_id ?Are you aware of modplsql when i executed the query the result is like
DECLARE
rc__ NUMBER;
simple_list__ OWA_UTIL.vc_arr;
complex_list__ OWA_UTIL.vc_arr;
BEGIN
OWA.init_cgi_env (:n__, :nm__, :v__);
HTP.htbuf_len := 84;
NULL;
NULL;
simple_list__ (1) := 'sys.%';
simple_list__ (2) := 'dbms\_%';
simple_list__ (3) := 'utl\_%';
simple_list__ (4) := 'owa\_%';
simple_list__ (5) := 'owa.%';
simple_list__ (6) := 'htp.%';
simple_list__ (7) := 'htf.%';
simple_list__ (8) := 'wpg_docload.%';
IF ((owa_match.match_pattern ('Oly_browse.oly_pattern ',
simple_list__,
complex_list__,
TRUE
THEN
rc__ := 2;
ELSE
NULL;
NULL;
oly_browse.oly_pattern (search_phrase => :search_phrase, --Oly_browse.oly_pattern is package name
btn => :btn,
p_qual => :p_qual,
p_bcat => :p_bcat,
p_stdy => :p_stdy,
p_bloc => :p_bloc,
z => :z
IF (WPG_DOCLOAD.is_file_download)
THEN
rc__ := 1;
WPG_DOCLOAD.get_download_file (:doc_info);
NULL;
NULL;
NULL;
COMMIT;
ELSE
rc__ := 0;
NULL;
NULL;
NULL;
COMMIT;
OWA.get_page (:data__, :ndata__);
END IF;
END IF;
:rc__ := rc__;
END; Edited by: vishnu prakash on Sep 8, 2010 10:16 PM -
Cannot use MAX function in PS Query
I am trying to use Query to select the max ( effdt ) from a table.
First, I use the 'Criteria' page to have
(1) Expression 1 = A.EFFDT - Effective Date, (2) Condition type = equal to, (3) Expression 2 = Subquery
Then the Subquery is:
(1) In the 'Field' page, I choose field E.EFFDT - Effective Date, (2) then click on 'EDIT', (3) then click on 'Max', (4) then click on 'OK' button
I then get this message: 'This field is an aggregate field but is being used in non-having criteria.(139,136). The query may fail if this is not corrected'
And as i try run anyway this query, i get this message:
SQL error. Stmt #: 5653 Error Position: 349 Return: 934 - ORA-00934: group function is not allowed here
A SQL error occurred. Please consult your system log for details.
Error in running query because of SQL Error, Code=934, Message=ORA-00934: group function is not allowed here (50,380)
NOTE: This max sql would work if i run using SqlPlus
How can i get Query to use max( effdt ) ?
Any clue anyone ? THANKSYes Using it as MAX is OK.
Problem is once you use it as MAX of a field, it wouln't allow this field for you to use it anymore.
A workaround i found that helped is to use the expression let's say 'MAX( a.JOB )' and use this as field.
This way, the system will allow me to use the JOBCODE field.
Thank you for all your helps as it leads me to the soln. -
Parameter passing to custom SQL query using PL/SQL FUNCTION
Hi
In order to pass a parameter to the query in custom folder of a business area I created a function and mapped it to the Custome query using Discoverer Desktop. There is no error in mapping as the system does not throw any error. When I am inputting the Parameter for the input values everytime the query doesnot return any rows.
Can anybody help in this regardHi,
I need to take the request Id as input from the user and then fetch only the data pertaining to that requet Id. As a lot of complex joins are involved I need to pass request id as parameter to the custome folder.
The package i greated:
CREATE OR REPLACE PACKAGE SETPARAM
AS
param1 varchar2(25);
param2 varchar2(25);
FUNCTION SET_PARAM1(p1 IN varchar2) RETURN NUMBER ;
FUNCTION GET_PARAM1 RETURN varchar2;
END SETPARAM;
CREATE OR REPLACE PACKAGE BODY SETPARAM AS
FUNCTION SET_PARAM1(p1 IN varchar2) RETURN NUMBER IS
BEGIN
fnd_client_info.set_org_context('138');
param1 := p1;
dbms_output.put_line(param1);
RETURN 1;
END;
FUNCTION GET_PARAM1 RETURN varchar2 AS
BEGIN
RETURN param1;
END;
END SETPARAM;
I registered the set_param1 function as a pl/sql function in discoverer admin.
This function is called on the condition associated with the parameter in Discoverer Desktop when i run the report.
In the custom folder query i have this piece in the where clause
WHERE tnfo.request_id = NVL(APPS.SETPARAM.GET_PARAM1,7383588)
And everytime i get the data pertaining to request id =7383588,
Please suggest where i went wrong
thanks
Ashwini -
SQL query using Group by and Aggregate function
Hi All,
I need your help in writing an SQL query to achieve the following.
Scenario:
I have table with 3 Columns. There are 3 possible values for col3 - Success, Failure & Error.
Now I need a query which can give me the summary counts for distinct values of col3 for each GROUP BY of col1 and col2 values. When there are no values for col3 then it should return ZERO count.
Example Data:
Col1 Col2 Col3
abc 01 success
abc 02 success
abc 01 success
abc 01 Failure
abc 01 Error
abc 02 Failure
abc 03 Error
xyz 07 Failure
Required Output:
c1 c2 s_cnt F_cnt E_cnt (Heading)
abc 01 2 1 1
abc 02 1 1 0
abc 03 0 0 1
xyz 07 0 1 0
s_cnt = Success count; F_cnt = Failure count; E_cnt = Error count
Please note that the output should have 5 columns with col1, col2, group by (col1,col2)count(success), group by (col1,col2)count(failure), group by (col1,col2)count(error)
and where ever there are NO ROWS then it should return ZERO.
Thanks in advance.
Regards,
ShivaHi,
user13015050 wrote:
Thanks TTT. Unfortunately I cannot use this solution because I have huge data for this.T's solution is basically the same as mine. The first 23 lines just simulates your table. Since you actually have a table, you would start with T's line 24:
SELECT col1 c1, col2 c2, SUM(decode(col3, 'success', 1, 0)) s_cnt, ...
user13015050 wrote:Thanks a lot Frank. It helped me out. I just did some changes to this as below and have no issues.
SELECT col1
, col2
, COUNT ( CASE
WHEN col3 = 'SUCCESS'
THEN 1
END
) AS s_cnt
, COUNT ( CASE
WHEN col3 = 'FAILED'
THEN 1
END
) AS f_cnt
, COUNT ( CASE
WHEN col3 = 'ERROR'
THEN 1
END
) AS e_cnt
FROM t1
WHERE c2 in ('PURCHASE','REFUND')
and c4 between to_date('20091031000000','YYYYMMDDHH24MISS') AND to_date('20100131235959','YYYYMMDDHH24MISS')
GROUP BY c1, c2
ORDER BY c1, c2;
Please let me know if you see any issues in this query.It's very hard to read.
This site normally compresses spaces. Whenever you post formatted text (such as queries or results) on this site, type these 6 characters:
\(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
Also, post exactly what you're using. The code above is SELECTing col1 and col2, but there's no mention of either in the GROUP BY clause, so I don't believe it's really what you're using.
Other than that, I don't see anything wrong or suspicious in the query.
Maybe you are looking for
-
When I try and pull up my iBooks I see my iBook shelf for about one second and then it goes to,white page and I can not get into books at all. Any suggestions??
-
How to install Windows 8.1 on Macbook Pro
I have a 13-inch Mid 2010 MacBook Pro operating on OS X Mavericks 10.9.2. I recently purchased Windows 8.1 as I was told by the Geek squad I could install it on my MacBook Pro. I keep getting this message every time I try to run BootCamp I get this:
-
Numbering in InDesign 5.5 - name index
Indesign 5.5. How to change the numbering style in the name index?
-
I have just bought the ipod touch 5th generation. I have used the rear camera and zoomed in for the photo. However the photo taken by the camera is not the one shown on the screen. So for example I am taking a picture of the tree I zoom in on the lea
-
hi Is there any limitations in EasyDms on how many documents can be stored in a structure or how many structures you can have.