Query using NTILE function
Is there any better way to write this query:
SELECT
MIN(EMPNO) "StartEmpno",
MAX(EMPNO) "EndEmpno",
partition
FROM
SELECT
EMPNO,
NTILE(20) OVER (ORDER BY EMPNO ASC ) as partition
FROM
(SELECT
EMPNO
FROM
EMP1
WHERE DEPTNO = 20
GROUP BY EMPNO
GROUP BY
partition
Well, one would assume that a column named empno in the emp table would be unique. If it was unique, the results would have been the same.
Well, this doesn't end up being much different that your original, but I would use distinct in the innermost inline view instead of a grouping one level above that:
select min(empno) "StartEmpno",
max(empno) "EndEmpno",
partition
from (select empno,
ntile(20) over (order by empno) partition
from (select distinct empno
from emp1
where deptno = 20))
group by partition;
Similar Messages
-
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. -
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
DeannaIs 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 -
Query using analytics function in SQL
Hello,
I have a situation here .. kindly guide me..
There are 2 tables, Case table (summary table) and Task table (detailed table)
The structure of tables:
Case Table:
Case_ID,
Trans_CT, à(transaction count could be 1,2,3 ..any numeric value)
Case_Rec_ID (major cols required)
Task table:
Case_ID
Case_Rec_ID,
Task Name,
Work_group_name,
Ready_to_work_in (Yes/No),
Ready_to_work_ts
Lst_Upd_ts
A work group can contain multiple cases.
I need to find out the # of ready_to_work transactions per case and roll it up to work group level.
The transaction Count is given at Case level (it is predefined in the source application;need not bother about how the value arrived;) if we do a join between case and task table , trans_ct appears for all the tasks. But there is a business rule for calculating the # of transactions(summation).
A case contains several tasks like for ex. & corresponding ready to work indicator like below
Case1 – Task 1 Y
Task2 Y
Task3 N
Task4 Y
Task5 Y
Case2 - Task 1 Y
Task2 Y
Task3 N
Task4 Y
Task5 N
If the RTW indicator is N for the last or recent task within the case then it can be ignored.
If the RTW indicator is Y for the last or recent task then we need consider the “trans_ct” value as # of RTW transaction for that case.
So Case 2 shall be ignored.
In Case 1, you can find the RTW flag has switched from Y-N-Y. If there is a switch of RTW flag within the case from Y to N then to Y and the last or recent tasks RTW flag is Y then we need to account for the number of switches & consider the corresponding “trans_ct” value. (# of switches * trans_ct)
Let’s say the trans_ct is 3 for Case 1. Now in this scenario, the # of RTW transactions would be (2*3=6 ).
Now I need to develop a query that can handle this scenario and roll up to work group level.
Tried the analytic functions lag,lead and first value, last value…but still trying to figure out the logic to handle this case1.
FYI- The Tasks need to be ordered by last_upd_ts
Please can you help me with the query.
Thanks
VinothAre you after something like this ?
with
cases as
(select 1 case_id,3 trans_ct,5 case_rec_id from dual union all
select 2,4,5 from dual union all
select 3,1,4 from dual union all
select 4,2,5 from dual
tasks as
(select 1 case_id,1 case_rec_id,'task 1' task_name,'g 1' work_group_name,'Y' ready_to_work_in,sysdate - 20 ready_to_work_ts,sysdate - 20 lst_upd_ts from dual union all
select 1,2,'task 2','g 1','Y',sysdate - 20,sysdate - 18 from dual union all
select 1,3,'task 3','g 1','N',sysdate - 20,sysdate - 17 from dual union all
select 1,4,'task 4','g 1','Y',sysdate - 16,sysdate - 15 from dual union all
select 1,5,'task 5','g 1','Y',sysdate - 16,sysdate - 12 from dual union all
select 2,1,'task 1','g 1','Y',sysdate - 18,sysdate - 18 from dual union all
select 2,2,'task 2','g 1','Y',sysdate - 16,sysdate - 16 from dual union all
select 2,3,'task 3','g 1','N',sysdate - 12,sysdate - 12 from dual union all
select 2,4,'task 4','g 1','Y',sysdate - 11,sysdate - 11 from dual union all
select 2,5,'task 5','g 1','N',sysdate - 10,sysdate - 10 from dual union all
select 3,1,'task 3','g 2','Y',sysdate - 13,sysdate - 13 from dual union all
select 3,2,'task 5','g 2','N',sysdate - 13,sysdate - 12 from dual union all
select 3,3,'task 1','g 2','N',sysdate - 13,sysdate - 11 from dual union all
select 3,4,'task 2','g 2','Y',sysdate - 13,sysdate - 10 from dual union all
select 4,1,'task 1','g 1','Y',sysdate - 20,sysdate - 20 from dual union all
select 4,2,'task 2','g 1','N',sysdate - 20,sysdate - 17 from dual union all
select 4,3,'task 3','g 1','Y',sysdate - 15,sysdate - 15 from dual union all
select 4,4,'task 4','g 1','N',sysdate - 15,sysdate - 13 from dual union all
select 4,5,'task 5','g 1','Y',sysdate - 15,sysdate - 10 from dual
CASE_ID
TRANS_CT
CASE_REC_ID
1
3
5
2
4
5
3
1
4
4
2
5
CASE_ID
CASE_REC_ID
TASK_NAME
WORK_GROUP_NAME
READY_TO_WORK_IN
READY_TO_WORK_TS
LST_UPD_TS
1
1
task 1
g 1
Y
09/13/2013
09/13/2013
1
2
task 2
g 1
Y
09/13/2013
09/15/2013
1
3
task 3
g 1
N
09/13/2013
09/16/2013
1
4
task 4
g 1
Y
09/17/2013
09/18/2013
1
5
task 5
g 1
Y
09/17/2013
09/21/2013
2
1
task 1
g 1
Y
09/15/2013
09/15/2013
2
2
task 2
g 1
Y
09/17/2013
09/17/2013
2
3
task 3
g 1
N
09/21/2013
09/21/2013
2
4
task 4
g 1
Y
09/22/2013
09/22/2013
2
5
task 5
g 1
N
09/23/2013
09/23/2013
3
1
task 3
g 2
Y
09/20/2013
09/20/2013
3
2
task 5
g 2
N
09/20/2013
09/21/2013
3
3
task 1
g 2
N
09/20/2013
09/22/2013
3
4
task 2
g 2
Y
09/20/2013
09/23/2013
4
1
task 1
g 1
Y
09/13/2013
09/13/2013
4
2
task 2
g 1
N
09/13/2013
09/16/2013
4
3
task 3
g 1
Y
09/18/2013
09/18/2013
4
4
task 4
g 1
N
09/18/2013
09/20/2013
4
5
task 5
g 1
Y
09/18/2013
09/23/2013
switches as
(select case_id,case_rec_id,task_name,work_group_name,ready_to_work_in,ready_to_work_ts,lst_upd_ts,switch
from (select case_id,case_rec_id,task_name,work_group_name,ready_to_work_in,ready_to_work_ts,lst_upd_ts,
case when ready_to_work_in = 'N'
and lag(ready_to_work_in) over (partition by case_id order by lst_upd_ts) = 'Y'
and lead(ready_to_work_in) over (partition by case_id order by lst_upd_ts) = 'Y'
then 2
end switch,
first_value(ready_to_work_in) over (partition by case_id order by lst_upd_ts desc) last_rtw
from tasks
where last_rtw = 'Y'
CASE_ID
CASE_REC_ID
TASK_NAME
WORK_GROUP_NAME
READY_TO_WORK_IN
READY_TO_WORK_TS
LST_UPD_TS
SWITCH
1
1
task 1
g 1
Y
09/13/2013
09/13/2013
1
2
task 2
g 1
Y
09/13/2013
09/15/2013
1
3
task 3
g 1
N
09/13/2013
09/16/2013
2
1
4
task 4
g 1
Y -
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; -
Query using Analytical Function
/*Hi there, i have the following table:*/
create table test (charcode varchar2(10),numberv number,father varchar2(10));
insert into test values('1',null,null); // Level 1
insert into test values('1.1',null,'1'); // Level 2
insert into test values('1.1.1',10,'1.1'); // Level 3
insert into test values('1.1.2',50,'1.1'); // Level 3
insert into test values('1.2',100,'1'); // Level 2
I want the following result
charcode , numberv
1 160
1.1 60
1.1.1 10
1.1.2 50
1.2 100
The real table has more than 1,000,000 and i have more then 8 levels, without analytical sum, it spend more than 3 hours to process, and i know that with analytical way it should spend less than 15 minutes.
I have a ideia on how to start: /*
select charcode,sum(numberv) over(partition father order by charcode desc)
order by charcode desc;
/* but this result it´s far way from what i expect ( the charcode 1 wasn´t populate and other values appears different values than i want
Thanks
Hélio*/here is your query. it will work for charcode between 1 and 9999.9999.9999.9999
of course you could extend it
this use regexp, but you could also use substr and instr.
select charcode,
numberv,
decode(length(charcode)-length(replace(charcode,'.')),
0,
sum(NUMBERV) over (partition by
substr(
replace(regexp_replace(
regexp_replace(
regexp_replace('.'||replace(charcode,'.','..')||'.',
'\.([0-9]{1})\.' , '.000\1.'),
'\.([0-9]{2})\.' , '.00\1.'),
'\.([0-9]{3})\.' , '.0\1.'),'.')
,1, 4)
1,
sum(NUMBERV) over (partition by
substr(
replace(regexp_replace(
regexp_replace(
regexp_replace('.'||replace(charcode,'.','..')||'.',
'\.([0-9]{1})\.' , '.000\1.'),
'\.([0-9]{2})\.' , '.00\1.'),
'\.([0-9]{3})\.' , '.0\1.'),'.')
,5, 4)
2,
sum(NUMBERV) over (partition by
substr(
replace(regexp_replace(
regexp_replace(
regexp_replace('.'||replace(charcode,'.','..')||'.',
'\.([0-9]{1})\.' , '.000\1.'),
'\.([0-9]{2})\.' , '.00\1.'),
'\.([0-9]{3})\.' , '.0\1.'),'.')
,9, 4)
3,
sum(NUMBERV) over (partition by
substr(
replace(regexp_replace(
regexp_replace(
regexp_replace('.'||replace(charcode,'.','..')||'.',
'\.([0-9]{1})\.' , '.000\1.'),
'\.([0-9]{2})\.' , '.00\1.'),
'\.([0-9]{3})\.' , '.0\1.'),'.')
,13, 4)
4,
sum(NUMBERV) over (partition by
substr(
replace(regexp_replace(
regexp_replace(
regexp_replace('.'||replace(charcode,'.','..')||'.',
'\.([0-9]{1})\.' , '.000\1.'),
'\.([0-9]{2})\.' , '.00\1.'),
'\.([0-9]{3})\.' , '.0\1.'),'.')
,17, 4)
) "sum"
from test
order by
replace(regexp_replace(
regexp_replace(
regexp_replace('.'||replace(charcode,'.','..')||'.',
'\.([0-9]{1})\.' , '.000\1.'),
'\.([0-9]{2})\.' , '.00\1.'),
'\.([0-9]{3})\.' , '.0\1.'),'.')
CHARCODE NUMBERV sum
1 160
1.1 60
1.1.1 10 10
1.1.2 50 50
1.2 100 100I hope you appreciate !
Regards
Laurent -
Using Aggregate function in queries
Hi all,
Please take a look on this query and suggest me why i'm getting the error..
This is my simple query using aggregate function in it..
SELECT T1.NAME, T1.DESCRIPTION, SUM(T2.QUANTITY)
FROM TABLE1 T1, TABLE2 T2
WHERE T1.ID=T2.ID
GROUP BY T1.NAME, T1.DESCRIPTION
Above query added with a sub-query in the select segment..
SELECT T1.NAME, T1.DESCRIPTION, SUM(T2.QUANTITY), (SELECT AVG(T3.PRICE) FROM TABLE1 TT1, TABLE3 T3 WHERE TT1.ID=T3.ID AND TT1.ID=T1.ID) AV_PRICE
FROM TABLE1 T1, TABLE2 T2
WHERE T1.ID=T2.ID
GROUP BY T1.NAME, T1.DESCRIPTION
When i add a sub-query which has aggregate function in it, i'm getting the 'ORA-00979: not a GROUP BY expression' error.What is your DB Version. Your query works without any issue in my DB. I used WITH clause to create the sample data. The query highlighted in BLUE is the actual query.
SQL> select * from v$version where rownum = 1;
BANNER
Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi
SQL> with table1
2 as
3 (
4 select 1 id, 'karthick' name, 'user name' description from dual
5 ),
6 table2
7 as
8 (
9 select 1 id, 100 quantity from dual
10 ),
11 table3
12 as
13 (
14 select 1 id, 10 price from dual
15 )
16 select t1.name
17 , t1.description
18 , sum(t2.quantity)
19 , (
20 select avg(t3.price)
21 from table1 tt1
22 , table3 t3
23 where tt1.id = t3.id
24 and tt1.id = t1.id
25 ) av_price
26 from table1 t1
27 , table2 t2
28 where t1.id = t2.id
29 group
30 by t1.name
31 , t1.description;
NAME DESCRIPTI SUM(T2.QUANTITY) AV_PRICE
karthick user name 100 10
SQL> -
[b]Using Analytic functions...[/b]
Hi All,
I need help in writing a query using analytic functions.
Foll is my scenario. I have a table cust_points
CREATE TABLE cust_points
( cust_id varchar2(10),
pts_dt date,
reward_points number(3),
bal_points number(3)
insert into cust_points values ('ABC',01-MAY-2004',5, 15)
insert into cust_points values ('ABC',05-MAY-2004',3, 12)
insert into cust_points values ('ABC',09-MAY-2004',3, 9)
insert into cust_points values ('XYZ',02-MAY-2004',8, 4)
insert into cust_points values ('XYZ',03-MAY-2004',5, 1)
insert into cust_points values ('JKL',10-MAY-2004',5, 11)
I want a result set which shows for each customer, the sum of reward his/her points
but balance points as of the last date. So for the above I should have foll results
cust_id reward_pts bal_points
ABC 11 9
XYZ 13 1
JKL 5 11
I having tried using last_value(), for eg
Select cust_id, sum(reward_points), last_value(bal_points) over (partition by cust_id)...but run into grouping errors.
Can anyone help ?try this...
SELECT a.pkcol,
nvl(SUM(b.col1),0) col1,
nvl(SUM(b.col2),0) col2,
nvl(SUM(b.col3),0) col3
FROM table1 a, table2 b, table3 c
WHERE a.pkcol = b.plcol(+)
AND a.pkcol = c.pkcol
GROUP BY a.pkcol;
SQL> select a.deptno,
2 nvl((select sum(sal) from test_emp b where a.deptno = b.deptno),0) col1,
3 nvl((select sum(comm) from test_emp b where a.deptno = b.deptno),0) col2
4 from test_dept a;
DEPTNO COL1 COL2
10 12786 0
20 13237 738
30 11217 2415
40 0 0
99 0 0
SQL> select a.deptno,
2 nvl(sum(b.sal),0) col1,
3 nvl(sum(b.comm),0) col2
4 from test_dept a,test_emp b
5 where a.deptno = b.deptno
6 group by a.deptno;
DEPTNO COL1 COL2
30 11217 2415
20 13237 738
10 12786 0
SQL> select a.deptno,
2 nvl(sum(b.sal),0) col1,
3 nvl(sum(b.comm),0) col2
4 from test_dept a,test_emp b
5 where a.deptno = b.deptno(+)
6 group by a.deptno;
DEPTNO COL1 COL2
10 12786 0
20 13237 738
30 11217 2415
40 0 0
99 0 0
SQL> -
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 return whole number using round function
hi
can i get sql query using round function how to return whole number valueHi welcome to the forum. if you want whole number value what does it mean
1. whether you want the whole number greator than or eqaul to that number example for 12.6 you want 12 or 13
see below example
1. SQL> select round(12.5) from dual;
ROUND(12.5)
13
2. SQL> select round(12.4) from dual;
ROUND(12.4)
12
3. SQL> select floor(12.5) from dual;
FLOOR(12.5)
12
4. SQL> select floor(12.4) from dual;
FLOOR(12.4)
12
floor will always give you a round value which is a integer or whole number less than or equal to but output of rond will differ if the value is greator than 12.5 it will give 13 but if it is less than 12.5 it will give 12, so depending on your requirement you can choose which function to use. similarly if you always want to get the whole number greator than the number you can use ceil as below
SQL> select ceil(12.3) from dual;
CEIL(12.3)
13
SQL> select ceil(12.8) from dual;
CEIL(12.8)
13 -
Self-join query to Analytical function query
Hi All,
I have converted a self-join query to Analytical function query due to the performance reasons.
Query which is using Analytical function is giving the correct count as I compared it with query using Self-Join. Can you please tell what is wrong in the query.
==========================
Query using Self-Join
select count(1)
From (select t1.*, max(t1.dw_creation_dt) over (partition by t1.empl_id) pers_max_date
from ohr_pers_curr t1 ) pers
, (select t2.*, max(t2.dw_creation_dt) over (partition by t2.empl_id, t2.empl_rcd) job_max_date
from OHR_JOB_CURR t2) job
where pers.empl_id = job.empl_id
and pers.dw_creation_dt=pers.pers_max_date
and job.dw_creation_dt=job.job_max_date
and job.dummy_row_flag = 'N'
and pers.dw_creation_rsn_cd in ('N', 'U')
and job.dw_creation_rsn_cd in ('N', 'U')
================================================
Query Using Analytical function
select count(1)
From (select t1.*, max(t1.dw_creation_dt) over (partition by t1.empl_id) pers_max_date
from ohr_pers_curr t1 ) pers
, (select t2.*, max(t2.dw_creation_dt) over (partition by t2.empl_id, t2.empl_rcd) job_max_date
from OHR_JOB_CURR t2) job
where pers.empl_id = job.empl_id
and pers.dw_creation_dt=pers.pers_max_date
and job.dw_creation_dt=job.job_max_date
and job.dummy_row_flag = 'N'
and pers.dw_creation_rsn_cd in ('N', 'U')
and job.dw_creation_rsn_cd in ('N', 'U')
==================================Hi David,
The base is same but the problem is different.
As far as implementation concern these queries looks same, but when I see there counts, they do not match. I do not have any reason why this happening.
Regards
Gaurav -
Help to write using anlytical functions or singe count instead of many
HI,
Could you some one help to write as single count instead of many (.Or) Is there any way to write below query using analytical functions?
SELECT paper_code,paper_code_description, numCandidates, cast(numAwaitingApproval as varchar2(10)) as numAwaitingApproval, (numawaitingtrans + numawaitingibtran) as numAwaitingSubmission, (numibsub + numsub) as numSubmittedForMarking
FROM(
SELECT e.paper_code,
translate_paper(e.paper_code,:v_year,:v_month,:v_iblanguage,:v_paper_type) AS paper_code_description,
COUNT(e.candidate) AS numcandidates,
COUNT(DECODE(status, 'AWAITING AUTHENTICATION',1)) AS numAwaitingApproval,
COUNT(DECODE(status, 'AWAITING TRANSFER',1)) AS numawaitingtrans,
COUNT(DECODE(status, 'AWAITING IB TRANSFER',1)) AS numawaitingibtran,
COUNT(DECODE(status, 'SUBMITTED',1)) AS numsub,
COUNT(DECODE(status, 'IB SUBMITTED',1)) AS numibsub
FROM e_assessment_cands e,
candidate_component_reg ccr,
person_subject_session pss
WHERE e.year = :v_year
AND e.month = :v_month
AND e.e_coursework = :v_e_coursework
AND e.school_code = :v_school_code
AND ccr.split_session_year = e.year
AND ccr.split_session_month = e.month
AND ccr.candidate = e.candidate
AND ccr.paper_code = e.paper_code
AND ccr.subject =:v_subject
AND ccr.subject_option =COALESCE(:v_subject_option,ccr.subject_option)
AND ccr.lvl =COALESCE(:v_lvl,ccr.lvl)
AND ccr.language =COALESCE(:v_language,ccr.language)
AND ccr.component =COALESCE(:v_component,ccr.component)
AND pss.year = ccr.split_session_year
AND pss.month = ccr.split_session_month
AND pss.subject = ccr.subject
AND pss.lvl = ccr.lvl
AND pss.subject_option = ccr.subject_option
AND pss.language = ccr.language
AND pss.role = :v_role
AND pss.person_code = :v_person_code
GROUP BY e.paper_code)Hi,
user575115 wrote:
HI,
Could you some one help to write as single count instead of many (.Or) If you're using Oracle 11, look at SELECT ... PIVOT.
If you'd like help. post CREATE TABLE and INSERT statements for some sample data, and the results you want from that data.
Always say which version of Oracle you're using.
Given that you need numCnadidates and numAwaitingApproval, using COUNT twice seems to be the simplest and most efficient way to do it.
If you don't need the other COUNTs, such as numawaitingtrans, then don't compute them.
Is there any way to write below query using analytical functions?Analytic functions can give you a COUNT without reducing the result set to one row per group. It lookw like you do want to reduce the result set to one row per group, however, so I don't see how analytic functions would help in this problem. -
A query regarding synchronised functions, using shared object
Hi all.
I have this little query, regarding the functions that are synchronised, based on accessing the lock to the object, which is being used for synchronizing.
Ok, I will clear myself with the following example :
class First
int a;
static int b;
public void func_one()
synchronized((Integer) a)
{ // function logic
} // End of func_one
public void func_two()
synchronized((Integer) b)
{ / function logic
} // End of func_two
public static void func_three()
synchronized((Integer) a)
{ // function logic
} // End of func_three, WHICH IS ACTUALLY NOT ALLOWED,
// just written here for completeness.
public static void func_four()
synchronized((Integer) b)
{ / function logic
} // End of func_four
First obj1 = new First();
First obj2 = new First();
Note that the four functions are different on the following criteria :
a) Whether the function is static or non-static.
b) Whether the object on which synchronization is based is a static, or a non-static member of the class.
Now, first my-thoughts; kindly correct me if I am wrong :
a) In case 1, we have a non-static function, synchronized on a non-static object. Thus, effectively, there is no-synchronisation, since in case obj1 and obj2 happen to call the func_one at the same time, obj1 will obtain lock for obj1.a; and obj2 will obtain lock to obj2.a; and both can go inside the supposed-to-be-synchronized-function-but-actually-is-not merrily.
Kindly correct me I am wrong anywhere in the above.
b) In case 2, we have a non-static function, synchronized on a static object. Here, again if obj1, and obj2 happen to call the function at the same time, obj1 will try to obtain lock for obj1.a; while obj2 will try to obtain lock for obj2.a. However, since obj1.a and obj2.a are the same, thus we will indeed obtain sychronisation.
Kindly correct me I am wrong anywhere in the above.
c) In case 3, we have a static function , synchronized on a non-static object. However, Java does not allow functions of this type, so we may safely move forward.
d) In case 4, we have a static function, synchronized on a static object.
Here, again if obj1, and obj2 happen to call the function at the same time, obj1 will try to obtain lock for obj1.a; while obj2 will try to obtain lock for obj2.a. However, since obj1.a and obj2.a are the same, thus we will indeed obtain sychronisation. But we are only partly done for this case.
First, Kindly correct me I am wrong anywhere in the above.
Now, I have a query : what happens if the call is made in a classically static manner, i.e. using the statement "First.func_four;".
Another query : so far we have been assuming that the only objects contending for the synchronized function are obj1, and obj2, in a single thread. Now, consider this, suppose we have the same reference obj1, in two threads, and the call "obj1.func_four;" happens to occur at the same time from each of these threads. Thus, we have obj1 rying to obtain lock for obj1.a; and again obj1 trying to obtain lock for obj1.a, which are the same locks. So, if obj1.a of the first thread obtains the lock, then it will enter the function no-doubt, but the call from the second thread will also succeed. Thus, effectively, our synchronisation is broken.
Or am I being dumb ?
Looking forward to replies..
Ashutosha) In case 1, we have a non-static function, synchronized on a non-static object. Thus, effectively, there is no-synchronisationThere is no synchronization between distinct First objects, but that's what you specified. Apart from the coding bug noted below, there would be synchronization between different threads using the same instance of First.
b) In case 2, we have a non-static function, synchronized on a static object. Here, again if obj1, and obj2 happen to call the function at the same time, obj1 will try to obtain lock for obj1.a; while obj2 will try to obtain lock for obj2.a.obj1/2 don't call methods or try to obtain locks. The two different threads do that. And you mean First.b, not obj1.b and obj2.b, but see also below.
d) In case 4, we have a static function, synchronized on a static object. Here, again if obj1, and obj2 happen to call the function at the same time, obj1 will try to obtain lock for obj1.a; while obj2 will try to obtain lock for obj2.a.Again, obj1/2 don't call methods or try to obtain locks. The two different threads do that. And again, you mean First.b. obj1.b and obj2.b are the same as First.b. Does that make it clearer?
Now, I have a query : what happens if the call is made in a classically static manner, i.e. using the statement "First.func_four;".That's what happens in any case whether you write obj1.func_four(), obj2.func)four(), or First.func_four(). All these are identical when func_four(0 is static.
Now, consider this, suppose we have the same reference obj1, in two threads, and the call "obj1.func_four;" happens to occur at the same time from each of these threads. Thus, we have obj1 rying to obtain lock for obj1.aNo we don't, we have a thread trying to obtain the lock on First.b.
and again obj1 trying to obtain lock for obj1.aYou mean obj2 and First.b, but obj2 doesn't obtain the lock, the thread does.
which are the same locks. So, if obj1.a of the first thread obtains the lock, then it will enter the function no-doubt, but the call from the second thread will also succeed.Of course it won't. Your reasoning here makes zero sense..Once First.b is locked it is locked. End of story.
Thus, effectively, our synchronisation is broken.No it isn't. The second thread will wait on the same First.b object that the first thread has locked.
However in any case you have a much bigger problem here. You're autoboxing your local 'int' variable to a possibly brand-new Integer object every call, so there may be no synchronization at all.
You need:
Object a = new Object();
static Object b = new Object(); -
When using TODATE function MDX query is not correctly generated
Essbase 9.3.1.2 and OBIEE 10.1.3.4.1.
When using TODATE function MDX query is not correctly generated.
This leads to unexpected values not only on cumulative columns in report (generated with TODATE), but also other columns (calculated with AGO function or directly read from cube) have incorrect values.
The problem occurs when you filter on a column that is not in the select list. If you filter on just one level of dimension, results are fine. You can filter on multiple dimensions as long as you filter on just one level of each dimension.
If you filter on two or more levels of one dimension, than results are not correct. In some cases results for TODATE column are all zeros, in some cases it is a random value returned by Essbase (same random value for all rows of that column), and in some cases BI Server returns an error:
State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. Essbase Error: Network error [10054]: Cannot Send Data (HY000).
Here is generated MDX code:
With
set [Grupe proizvoda2] as '{[Grupe proizvoda].[N4]}'
set [Grupe proizvoda4] as 'Generate([Grupe proizvoda2], Descendants([Grupe proizvoda].currentmember, [Grupe proizvoda].Generations(4), leaves))'
set [Segmentacija2] as '{[Segmentacija].[RETAIL]}'
set [Segmentacija4] as 'Filter(Generate({[Segmentacija2]}, Descendants([Segmentacija].currentmember, [Segmentacija].Generations(4),SELF), ALL), ([Segmentacija].CurrentMember IS [Segmentacija].[AFFLUENT]))'
set [Vrijeme3] as '{[Vrijeme].[MJESEC_4_2009]}'
member [Segmentacija].[SegmentacijaCustomGroup]as 'Sum([Segmentacija4])', SOLVE_ORDER = AGGREGATION_SOLVEORDER
member [Accounts].[MS1] as '(ParallelPeriod([Vrijeme].[Gen3,Vrijeme],2,[Vrijeme].currentmember), [Accounts].[Trosak kapitala])'
member [Accounts].[MS2] as '(ParallelPeriod([Vrijeme].[Gen3,Vrijeme],1,[Vrijeme].currentmember), [Accounts].[Trosak kapitala])'
member [Accounts].[MS3] as 'AGGREGATE({PeriodsToDate([Vrijeme].[Gen2,Vrijeme],[Vrijeme].currentmember)}, [Accounts].[Trosak kapitala])'
select
{ [Accounts].[Trosak kapitala],
[Accounts].[MS1],
[Accounts].[MS2],
[Accounts].[MS3]
} on columns,
NON EMPTY {crossjoin ({[Grupe proizvoda4]},{[Vrijeme3]})} properties ANCESTOR_NAMES, GEN_NUMBER on rows
from [NISE.NISE]
where ([Segmentacija].[SegmentacijaCustomGroup])
If you remove part with TODATE function, the results are fine. If you leave TODATE function, OBIEE returns an error mentioned above. If you manually modify variable SOLVE_ORDER and set value to, for example, 100 instead of AGGREGATION_SOLVEORDER, results are OK.
In all cases when this variable was modified in generated MDX, and query manually executed on Essabse, results were OK. This variable seems to be the possible problem.Hi,
Version is
BANNER
Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi
PL/SQL Release 10.2.0.5.0 - Production
CORE 10.2.0.5.0 Production
TNS for 64-bit Windows: Version 10.2.0.5.0 - Production
NLSRTL Version 10.2.0.5.0 - Production
Sorry, in my last post i forgot to mention that i already created a function based index but still it is not using because, there is a UNIQUE constraint on that column.
Thanks -
Error in using aggregate function in Outer Query in Siebel Analytics
Hi,
When I am using aggregate function in outer query in Siebel Analytics I am facing error.
Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P:OI2DL65P
State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 59111] The SQL statement must include a GROUP BY clause. (HY000)
Bellow is the code.
SELECT test1.username saw_0, test1.desg saw_1,COUNT (test2.querydate) saw_2
FROM (SELECT POSITION.CBL username,
POSITION.CBP desg
FROM "CM"
WHERE (POSITION.BPTCD = 'Marketing')
AND (POSITION.EDate =TIMESTAMP '1899-01-01 00:00:00'
) test1,
(SELECT users.UN username,
measures."Query Count" querycount,
measures."Max Total Time" secs,
topic.db dashboardname,
"Query Time".DATE querydate
FROM "Plan"
WHERE (topic."Dashboard Name" IN ('DS'))) test2
WHERE test2.username = LOWER (test1.username)
AND test2.dashboardname = 'DS'
GROUP BY test1.username, test1.desgShould your query be a valid SQL query?
I can't think that the query you have would be valid in a SQL plus window.
Chris
Maybe you are looking for
-
How do I sync multiple audio clips to one video clip?
I have video (with stereo audio from a camera mic), and for each take, there are also four additional mono audio tracks that line up with it. It was footage shot outdoors in the city, so I guess the filmmakers just wanted to have as many options for
-
Hi, I have a LOV with a query has a bind variable: select comp_plan_id,name from cn_comp_plans_all where sysdate between start_date and nvl(end_date,sysdate+1) and org_id = : 1 So I create a CO for this LOV , and in processRequest(), I pass the value
-
ITunes 11.1.4 installation failed with win7 professional
update of iTunes 11.1.3.8 to 11.1.5 failed. Old version was no longer available. MCV80.dll was no longer available. uninstall iTunes and efforts to install Version 11.1.4 failed Set back of system before iinstallation and start of itunes failed.How
-
8213 D1G no internet, no usb, only vga
Hello I have this second hand 8213 D1G. Tried to install windows on it. Windows works, but I have no internet. In the device manager section I see several ! and ?. At the 'ethernet line'. If I look for drivers in the properties tab, there is no d
-
Hi, i often use the feature SQL Query (PL/SQL Function Returning SQL Query). Sometimes there is an error in the query and zero rows are returned. It would be nice to see which SQL-Statement was used. I tried to copy the sql statment to an item on the