SUM OVER PARTITION BY condition?
I have a piece of SQL similar to:
SELECT person,
amount,
type,
SUM(amount) OVER (PARTITION BY person) sum_amount_person
FROM table_a
What I would like to be able to do is use a conditional PARTITION BY clause, so rather than partition and summing for each person I would like to be able to sum for each person where type = 'ABC'
I would expect the syntax to be something like
SELECT person,
amount,
type,
SUM(amount) OVER (PARTITION BY person WHERE type = 'ABC') sum_amount_person
FROM table_a
Is this possible? Or am I missing a much simpler solution?
Richard
The proposed query does not compile on my Windows Oracle 9.2.0.5 or 10.1. This could be generated by the ambiguty introduced by DECODE in the evaluation of query (does it filter the selected rows, or the rows summarized for each selected row, or both?).
I propose two alternatives. The requirements are not specific enough to allow me to choose between them.
SQL> SELECT * FROM table_a ORDER BY 1, 3;
PERSON AMOUNT TYP
john 12 abc
john 8 abc
john 20 def
mike 15 abc
mike 30 ghi
steve 30 abc
6 rows selected.
SQL> SELECT person,
2 amount,
3 type,
4 SUM(decode(type, 'ABC',amount, to_number(NULL)) OVER (PARTITION BY person) sum_amount_person
5 FROM table_a;
SUM(decode(type, 'ABC',amount, to_number(NULL)) OVER (PARTITION BY person) sum_amount_person
ERROR at line 4:
ORA-30483: window functions are not allowed here
SQL> SELECT person,
2 amount,
3 type,
4 CASE type WHEN 'abc' THEN SUM(amount) OVER (PARTITION BY person) END sum_amount_person
5 FROM table_a;
PERSON AMOUNT TYP SUM_AMOUNT_PERSON
john 12 abc 40
john 20 def
john 8 abc 40
mike 15 abc 45
mike 30 ghi
steve 30 abc 30
6 rows selected.
SQL> SELECT person,
2 amount,
3 type,
4 CASE type WHEN 'abc' THEN SUM(amount) OVER (PARTITION BY person, type) END sum_amount_person
5 FROM table_a;
PERSON AMOUNT TYP SUM_AMOUNT_PERSON
john 12 abc 20
john 8 abc 20
john 20 def
mike 15 abc 15
mike 30 ghi
steve 30 abc 30
6 rows selected.
Similar Messages
-
Analytical function SUM() OVER (PARTITION BY ) in Crosstab
I am trying to resolve this from a very long time. I have an amount column that has to be grouped on Year, but all the other columns grouped by month. I am trying to achieve this using analytic function SUM(Case when (Condition1 and Condition2) then Sum(Amount) else 0 end) OVER ( PARTITION BY Account, Year), Where Account, Sub Account are the left axis columns. Now, column displays the values correctly, but at different rows. This is confusing.............
For Ex: For Account 00001, there are 3 sub accounts 1000,2000,3000. For Sub account 3000, conditions 1 and 2 are satisfied, so it should display the Amount in the row corresponding to Sub account 3000, and 0 for remaining Sub Accounts. And the Total amount of all the sub accounts, which will be the same as amount for SubAccount 3000 should be displayed in the row corresponding to Account 00001.
But I get blank rows for 1000 and 3000 Sub accounts and Amount displayed in 2000 Sub account, and blank for Account 00001 also.
When I created the same workbook in Tabular form, the same amount is displayed for all the SubAccounts of a single Account.
When I used this CASE statement in TOAD, I figured that this is due to the Analytic function. When I use a group by clause as shown below instead of partition by, I get the results I need.
SELECT (Case when (Condition1 and Condition2) then Sum(Amount) else 0 end), Account, Sub Account FROM tables WHERE conditions GROUP BY Year, Account, Sub Account
But I cannot use groupby for whole SQL of the workbook as I need the other columns with page item 'MONTH' not 'Year'.
Could somebody please help me with this?Hi,
In your tabular form do you get the correct total display against all you subaccounts and account? If this correct then you can use case to ensure that the total is displayed only for the single account.
Once you have the correct totals working in a tabular form it is easier to re-produce what you want in a cross-tab.
Rod West -
PLSQL does not support 'Sum Over Partition'
I have something (and many obvious syntactical variations) like the following which works great in SQLPLUS but not in PLSQL:
select
table1.aField,
table2.bField,
sum (table1.type) over (partition by type)
from
table1, table2
where
aField = something;
PLSQL does not seem to like the "(" in from of the partition keyword.
I get the following PL/SQL error when I attempt to compile:
4/26 PLS-00103: Encountered the symbol "(" when expecting one of the following:
, fromWhat Oracle version are you running?
Is it Oracle8i?
Begining with Oracle9i, SQL parsers for SQL and PL/SQL were merged togather. Before 9i, many of the new features introduced in SQL were not recognized by the PL/SQL parser.
The following example works as expected on Oracle9i:
SQL> begin
2 for rec in (select deptno, ename, sum(sal) over (partition by deptno)total from scott.emp)
3 loop
4 dbms_output.put_line(rec.ename||' - '||rec.total) ;
5 end loop ;
6 end ;
7 /
CLARK - 8750
KING - 8750
MILLER - 8750
SMITH - 10875
ADAMS - 10875
FORD - 10875
SCOTT - 10875
JONES - 10875
ALLEN - 9400
BLAKE - 9400
MARTIN - 9400
JAMES - 9400
TURNER - 9400
WARD - 9400
PL/SQL procedure successfully completed.
SQL> disconnect
Disconnected from Oracle9i Enterprise Edition Release 9.2.0.3.0 - Production
With the Partitioning, OLAP and Oracle Data Mining options
JServer Release 9.2.0.3.0 - Production
SQL> -
Hi
I have an calculated field (age_group) which gives month age (0-2Y,2-4Y......)
I want to sum a measure (which has a sum aggragation rule in the repository) to show the sum of the measure over partition of age_group and the quarter (another dimension).
when i perform a calculated Item in the request SUM(measure) it gives wrong answers. i want actually to imitate the total option (which is calculated right) in a formula in order to use this formula column in the request
Any idea how to perform it?
ThanksHi
Thanks for your reply
I will try to explain exactly what i mean:
I have the following details
QTR Age_group Money
2006_Q3 0-2y 10000
2006_Q3 2-4Y 15000
2006_Q3 4-6Y 20000
2006_Q3 more_6 10000
Total 2006_Q3 55000
I want to calculate the total and to percent it as new column
meaning I want a new report that will look like this:
QTR Age_group Money Money_calc
2006_Q3 0-2y 10000 55000
2006_Q3 2-4Y 15000 55000
2006_Q3 4-6Y 20000 55000
2006_Q3 more_6 10000 55000
Thanks -
Case Statement in Analytic Function SUM(n) OVER(PARTITION BY x)
Hi Guys,
I have the following SQL that doesn't seem to consider the When clause I am using in the case staement inside the analytic function(SUM). Could somebody let me know why? and suggest the solution?
Select SUM(Case When (A.Flag = 'B' and B.Status != 'C') Then (NVL(A.Amount_Cr, 0) - (NVL(A.Amount_Dr,0))) Else 0 End) OVER (PARTITION BY A.Period_Year) Annual_amount
, A.period_year
, B.status
, A.Flag
from A, B, C
where A.period_year = 2006
and C.Account = '301010'
--and B.STATUS != 'C'
--and A.Flag = 'B'
and A.Col_x = B.Col_x
and A.Col_y = C.Col_y
When I use this SQL, I get
Annual_Amount Period_Year Status Flag
5721017.5 --------- 2006 ---------- C -------- B
5721017.5 --------- 2006 ---------- O -------- B
5721017.5 --------- 2006 ---------- NULL ----- A
And when I put the conditions in the where clause, I get
Annual_Amount Period_Year Status Flag
5721017.5 ---------- 2006 ---------- O -------- BHere are some scripts,
create table testtable1 ( ColxID number(10), ColyID number(10) , Periodname varchar2(15), Flag varchar2(1), Periodyear number(15), debit number, credit number)
insert into testtable1 values(1, 1000, 'JAN-06', 'A', 2006, 7555523.71, 7647668)
insert into testtable1 values(2, 1001, 'FEB-06', 'B', 2006, 112710, 156047)
insert into testtable1 values(3, 1002, 'MAR-06', 'A', 2006, 200.57, 22376.43)
insert into testtable1 values(4, 1003, 'APR-06', 'B', 2006, 0, 53846)
insert into testtable1 values(5, 1004, 'MAY-06', 'A', 2006, 6349227.19, 6650278.03)
create table testtable2 ( ColxID number(10), Account number(10))
insert into testtable2 values(1, 300100)
insert into testtable2 values(2, 300200)
insert into testtable2 values(3, 300300)
insert into testtable2 values(4, 300400)
insert into testtable2 values(5, 300500)
create table apps.testtable3 ( ColyID number(10), Status varchar2(1))
insert into testtable3 values(1000, 'C')
insert into testtable3 values(1001, 'O')
insert into testtable3 values(1002, 'C')
My SQL:
select t1.periodyear
, SUM(Case When (t1.Flag = 'B' and t3.Status != 'C') Then (NVL(t1.credit, 0) - (NVL(t1.debit,0))) Else 0 End) OVER (PARTITION BY t1.PeriodYear)
Annual_amount
, t1.flag
, t3.status
, t2.account
from testtable1 t1, testtable2 t2, testtable3 t3
where t1.colxid = t2.colxid
and t1.colyid = t3.colyid(+)
--and t1.Flag = 'B' and t3.Status != 'C'
Result:
PeriodYear ----- AnnualAmount ----- Flag ----- Status ----- Account
2006 ------------------ 43337 --------------- A ----------- C ---------- 300100
2006 ------------------ 43337 --------------- B ----------- O ---------- 300200
2006 ------------------ 43337 --------------- A ----------- C ---------- 300300
2006 ------------------ 43337 --------------- B ------------ ----------- 300400
2006 ------------------ 43337 --------------- A ------------ ----------- 300500
With condition "t1.Flag = 'B' and t3.Status != 'C'" in where clause instead of in Case statement, Result is (which is desired)
PeriodYear ----- AnnualAmount ----- Flag ----- Status ----- Account
2006 ------------------ 43337 --------------- B ----------- O ---------- 300200 -
Discoverer Plus - Lag / Over / Partition By / Order By (Conditional Syntax)
Good morning everybody
I have created the following syntax in Oracle Discoverer Plus and it works amazingly. However, I have a single problem.
This syntax gives me the comparison of two values (for instance: Jan.2010 values & Feb.2010 values). But it does not give me the value of all of the new records (for instance: if there is no values in Jan.2010, then it will not give me the value of Feb.2010). Hence, my report excludes all of the new records values.
If I am not mistaken, the below formulla will not be changed, but it needs some conditional syntax:
1. Compare syntax: if there is two similar records; and
2. Give the values of all the new records without any change in thier values
*(Amount-LAG(Amount,1)OVER(PARTITION BY "Sequence Number"ORDER BY "Sequence Number ASC))*
Thank very much in advance.
Mr. Zuhair Fardan
Kingdom of Bahrain
Email: [email protected]Zuhair,
change,
(Amount-LAG(Amount,1)OVER(PARTITION BY "Sequence Number"ORDER BY "Sequence Number ASC)){code}
to
{code}
(Amount-LAG(Amount,1,0)OVER(PARTITION BY "Sequence Number" ORDER BY "Sequence Number ASC))Note the extra zero in LAG(Amount,1,0). That's the default return value if nothing is found.
As it is you are subtracting null from the amount and getting null.
Hope that is helpful.
- James -
Issue with OBIEE ROW_NUMBER() OVER (PARTITION BY)
Hi All,
I am facing some issue with the ROW_NUMBER() OVER (PARTITION BY function in the query that is being generated. I am currently on version 11.1.1.6. I have 1 FACT and 1 Dimension table. Within the dimension I have create a level based hierarchy namely REGION -> GROUP - DIVISION etc. Now the problem is that the OBIEE automatically applies *"ROW_NUMBER() OVER (PARTITION BY T9.PRODUCT_TYPE_DESC, T130.DIVISION_DESC, T130.REGION_DESC ORDER BY T9.PRODUCT_TYPE_DESC ASC, T130.DIVISION_DESC ASC, T130.REGION_DESC ASC) "
to the query where in it is not required at it returns with 3 different row numbers. If i remove this line and the where clause I am able to get correct results however its not working whatever I do in the RPD. Please advise.
WITH
SAWITH0 AS (select D1.c1 as c1,
D1.c2 as c2,
D1.c3 as c3,
D1.c4 as c4,
D1.c5 as c5,
D1.c6 as c6
from
(select sum(T157.PL_GRAND_TOTAL) as c1,
sum(T157.TRANSACTION_AMT) as c2,
T130.DIVISION_DESC as c3,
T130.REGION_DESC as c4,
T130.GROUP_DESC as c5,
T9.PRODUCT_TYPE_DESC as c6,
ROW_NUMBER() OVER (PARTITION BY T9.PRODUCT_TYPE_DESC, T130.DIVISION_DESC, T130.REGION_DESC ORDER BY T9.PRODUCT_TYPE_DESC ASC, T130.DIVISION_DESC ASC, T130.REGION_DESC ASC) as c7
from
DIM_ALL_MODULES_REF T9,
DIM_MIS_TREE_REF T130,
DIM_DATE_SERIES T123,
FCT_ALL_MODULES_TRANS T157
where ( T9.SGK_MIS_ID = T130.SGK_MIS_ID and T9.SGK_MODULE_ID = T157.SGK_MODULE_ID and T123.SGK_TIME_ID = T157.SGK_TIME_ID and T123.TRANS_DATE between TO_DATE('2011-01-01 00:00:00' , 'YYYY-MM-DD HH24:MI:SS') and TO_DATE('2011-03-31 00:00:00' , 'YYYY-MM-DD HH24:MI:SS') )
group by T9.PRODUCT_TYPE_DESC, T130.DIVISION_DESC, T130.GROUP_DESC, T130.REGION_DESC
) D1
where ( D1.c7 = 1 ) ),
SACOMMON42934 AS (select T130.DIVISION_DESC as c2,
T130.REGION_DESC as c3,
T130.GROUP_DESC as c4,
T9.PRODUCT_TYPE_DESC as c5,
sum(T258.BEG_NMK_EQ_COST_AMT) as c6,
T123.TRANS_DATE as c7,
sum(T258.END_NMK_EQ_COST_AMT) as c8
from
DIM_ALL_MODULES_REF T9,
DIM_MIS_TREE_REF T130,
DIM_DATE_SERIES T123,
FCT_MODULES_BEG_END_BAL T258
where ( T123.SGK_TIME_ID = T258.SGK_TIME_ID and T9.SGK_MIS_ID = T130.SGK_MIS_ID and T9.SGK_MODULE_ID = T258.SGK_MODULE_ID and T258.PRODUCT_TYPE_ID = 2 and T123.TRANS_DATE between TO_DATE('2011-01-01 00:00:00' , 'YYYY-MM-DD HH24:MI:SS') and TO_DATE('2011-03-31 00:00:00' , 'YYYY-MM-DD HH24:MI:SS') )
group by T9.PRODUCT_TYPE_DESC, T123.TRANS_DATE, T130.DIVISION_DESC, T130.GROUP_DESC, T130.REGION_DESC),Hi Dhar,
Thanks for replying back. But the ROW_NUMBER thing is inserted with the "WITH SUPPORTED" clause only but that is something which are the default settings. However, I notice that ROW_NUMBER() OVER (PARTITION BY) lines are erratic and are not consistent. So sometimes the drill works properly when no ROW_NUMBER() OVER (PARTITION BY) is generated but other times data is wrong. I am not sure why this behaviour is erratic even though I select the same values.
This is surely a product problem as the condition where c7 = 1 filters the result and does not take into account all values.
Even when I do not use WITH_SUPPORTED clause the stitch does not happen properly. Please advice if this is ever going to be by Oracle or any work around for this?
Thanks -
How can i sum the columns by condition?
ID Type QTY
1 A 20
2 A 20
3 B 20
I want to some QTY group by A but I also need the ID column to identify the order of row.
How can I sum QTY group by A and the result is sort by ID ?
Thanks youWhats your expected output?
Is this the below?
Create Table test(id int,[Type] char(1), QTY int)
Insert into test Values(1,'A',20),
(2,'A',20),
(3,'B',20)
SElect *,SUM(qty)Over(partition by Type) From test Order by id
Drop table test -
How to use expression in over partition function
sum(a) over(partition by b order by c range between interval '1' day following and '7' day following)
the above query works fine
but i want to use like this
sum(a) over(partition by b order by c range between interval Trunc(Trunc(sysdate,'MONTH')+1,'MONTH') day following and '7' day following)
is it work ??Balaji.tk wrote:
is it work ??Have you tried it? If not, have a go. ;) -
Hi,
I'm trying to do something which I would guess is quite a common query, but after scratching my head and perusing the web I am still no closer to a solution.
I am running:
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
I'm looking to sum up a set of values, taking into account both a parent grouping and start and end dates.
For the parent grouping I am using:
+SUM([value]) over (Partition by [Parent] order by [Parent],[Child])+
And I was hoping to be able to extend this SUM to also handle the start and end dates, so the final output would contain a sum of the values for each different time period.
As an example, using the data below I'm trying to sum up the price of the components of a car over time:
row, product, component, rate, start date, end date
1, car, chassis, 180, 01/01/2000, 31/12/2009
2, car, chassis, 200, 01/01/2010, 01/01/2050
3, car, engine, 100, 01/01/2000, 01/01/2050
Notice there is a change of price for Component 'chassis', so the output I'm looking for is:
row, product, component, rate, start date, end date, sum
1, car, chassis, 180, 01/01/2000, 31/12/2009, 280
2, car, engine, 100, 01/01/2000, 31/12/2009, 280
3, car, chassis, 200, 01/01/2010, 01/01/2050, 300
4, car, engine, 100, 01/01/2010, 01/01/2050, 300
But in reality all I need is:
row, product, start date, end date, sum
1, car, 01/01/2000, 31/12/2009, 280
2, car, 01/01/2010, 01/01/2050, 300
Preferably the query would be in a view rather than a stored procedure, and it needs to be able to handle many 'products', 'components' and start/end dates.
All help most appreciated, and if any more info is required, please let me know.
Thanks,
JulianHi Frank,
Thanks for picking up this query, I'll try to explain my points in more detail:
+SUM([value]) over (Partition by [Parent] order by [Parent],[Child])+I don't see columns called value, parent or child in the sample data below.
Is value the same as rate? What are parent and child? In the example:
Product is the parent
Component is the child
Rate is the value
Whenever you have a problem, post CREATE TABLE and INSERT statments for your sample data.CREATE TABLE "REPOSITORY"."PRODUCT_RATES"
( "PRODUCT" VARCHAR2(255 BYTE),
"COMPONENT" VARCHAR2(255 BYTE),
"RATE" NUMBER(9,2),
"START_DATE" DATE,
"END_DATE" DATE
) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
TABLESPACE "SHOP_AREA" ;
insert into REPOSITORY.PRODUCT_RATES (PRODUCT, COMPONENT, RATE, START_DATE, END_DATE) values ('car', 'chassis', 180, to_date('01-01-2000','dd-mm-yyyy'), to_date('31-12-2009','dd-mm-yyyy'))
insert into REPOSITORY.PRODUCT_RATES (PRODUCT, COMPONENT, RATE, START_DATE, END_DATE) values ('car', 'chassis', 200, to_date('01-01-2010','dd-mm-yyyy'), to_date('01-01-2050','dd-mm-yyyy'))
insert into REPOSITORY.PRODUCT_RATES (PRODUCT, COMPONENT, RATE, START_DATE, END_DATE) values ('car', 'engine', 100, to_date('01-01-2000','dd-mm-yyyy'), to_date('01-01-2050','dd-mm-yyyy'))
Although the above short scenario highlights my issue, to expand on the example data set:
insert into REPOSITORY.PRODUCT_RATES (PRODUCT, COMPONENT, RATE, START_DATE, END_DATE) values ('family', 'wife', 500, to_date('01-01-2000','dd-mm-yyyy'), to_date('31-12-2001','dd-mm-yyyy'))
insert into REPOSITORY.PRODUCT_RATES (PRODUCT, COMPONENT, RATE, START_DATE, END_DATE) values ('family', 'wife', 999, to_date('01-01-2002','dd-mm-yyyy'), to_date('01-01-2050','dd-mm-yyyy'))
insert into REPOSITORY.PRODUCT_RATES (PRODUCT, COMPONENT, RATE, START_DATE, END_DATE) values ('family', 'baby', 250, to_date('01-01-2000','dd-mm-yyyy'), to_date('31-12-2004','dd-mm-yyyy'))
insert into REPOSITORY.PRODUCT_RATES (PRODUCT, COMPONENT, RATE, START_DATE, END_DATE) values ('family', 'baby', 500, to_date('01-01-2005','dd-mm-yyyy'), to_date('01-01-2050','dd-mm-yyyy'))
Notice there is a change of price for Component 'chassis', so the output I'm looking for is:
row, product, component, rate, start date, end date, sum
1, car, chassis, 180, 01/01/2000, 31/12/2009, 280
2, car, engine, 100, 01/01/2000, 31/12/2009, 280
3, car, chassis, 200, 01/01/2010, 01/01/2050, 300
4, car, engine, 100, 01/01/2010, 01/01/2050, 300Explain how you get 4 rows of output when the table contains only 3 rows. Are you saying that, because some row has end_date=31/12/2009, then any other row that includes that date has to be split into two, with one row ending on 31/12/2009 and the other one beginning on the next day?
Explain, step by step, how you get the values in the desired output, especially the last column.
But in reality all I need is:Sorry, I can;'t understand what you want.
Are you saying that the output above sould be acceptable, but the output below would be even better?
row, product, start date, end date, sum
1, car, 01/01/2000, 31/12/2009, 280
2, car, 01/01/2010, 01/01/2050, 300
Preferably the query would be in a view rather than a stored procedure, and it needs to be able to handle many 'products', 'components' and start/end dates.Include a couple of differtent products in your sample data and results.
I'm not sure what you want, but there's nothing in what you've said so far that makes me think a stored procedure would be needed.The only output I actually require is:
row, product, component, rate, start date, end date, sum
1, car, 01/01/2000, 31/12/2009, 280
2, car, 01/01/2010, 01/01/2050, 300and with the extended data set:
3, family, 750, 01/01/2000, 31/12/2001
4, family, 1249, 01/01/2002, 31/12/2004
5, family, 1499, 01/01/2005, 31/12/2050however, I was thinking that the data set would need to be somehow expanded to get to the above end result, hence why I included the 'middle step' of:
row, product, component, rate, start date, end date, sum
1, car, chassis, 180, 01/01/2000, 31/12/2009, 280
2, car, engine, 100, 01/01/2000, 31/12/2009, 280
3, car, chassis, 200, 01/01/2010, 01/01/2050, 300
4, car, engine, 100, 01/01/2010, 01/01/2050, 300however, this may be irrelevent.
By the way, there's no point in using the same expression in both the PARTITON BY and ORDER BY clauses of the same analytic function call. For example, if you "PARTITION BY parent", then, when "ORDER BY parent, child" is evaluated, rows will only be compared to other rows with the same parent, so they'll all tie for first place in "ORDER BY parent". OK, thanks.
So far I have got to:
select
sum(rate) over (partition by product) as sum,
a.*
from product_rates a
which results in:
SUM PRODUCT COMPONENT RATE START_DATE END_DATE
480 car engine 100 2000-01-01 00:00:00.0 2050-01-01 00:00:00.0
480 car chassis 200 2010-01-01 00:00:00.0 2050-01-01 00:00:00.0
480 car chassis 180 2000-01-01 00:00:00.0 2009-12-31 00:00:00.0
2249 family baby 250 2000-01-01 00:00:00.0 2004-12-31 00:00:00.0
2249 family wife 999 2002-01-01 00:00:00.0 2050-01-01 00:00:00.0
2249 family baby 500 2005-01-01 00:00:00.0 2050-01-01 00:00:00.0
2249 family wife 500 2000-01-01 00:00:00.0 2001-12-31 00:00:00.0
but this shows that all price variations for a component over time are being summed (e.g. car enging 100 + car chassis 200 + car chassis 180 = 480)
Hope that goes someway expaling my query better.
Also, quick query to improve my postings - how do i indent without making text ittallic, and how do you make code a different font?
Thanks again.
Julian -
Duplicate rows in over partition by
select * from zzz
id amt
1 10
1 20
2 5
2 6
3 10
select id, sum(amt) over (partition by id order by id) sum from zzz
1 30
1 30
2 11
2 11
3 10Why I'm getting duplicate rows??
Can't use distinct or group by as this is just a small demo and I'll be using my query as part of another complex join.partition by won't filter the results based on group. It shows the exact table rows. The use of this analytical function is you can use the group function without using the group by clause showing all records in the table and group funtion as well. So this is not showing duplicate data but showing the actual data.
If the data is to be filtered based on group, you can use explicitely group by clause.
Hope this helps -
Can we use partition with condition?
Hi,
I want to partition the table using a coumn, and some conditions on the columns. Can we do this?
Any suggesitions are welcome.
Thanks and regards
Gowtham Sen.Something like
1 select ename,
2 sal,
3 deptno,
4 lag( sal ) over ( partition by (case when deptno <= 15
5 then 'Low'
6 else 'HIGH'
7 end)
8 order by sal ) prev_sal
9* from emp
SCOTT @ nx102 JCAVE9420> /
ENAME SAL DEPTNO PREV_SAL
SMITH 800 20
JAMES 950 30 800
ADAMS 1100 20 950
WARD 1250 30 1100
MARTIN 1250 30 1250
TURNER 1500 30 1250
ALLEN 1600 30 1500
BLAKE 2850 30 1600
JONES 2975 20 2850
FORD 3000 20 2975
SCOTT 3000 20 3000
MILLER 1300 10
CLARK 2450 10 1300
KING 5000 10 2450
14 rows selected.
Elapsed: 00:00:00.04Justin -
Ssrs sum based upon a conditional statement
In an ssrs 2008 r2 report, I have the following code that totals a transaction amount:
=sum(cdec(Fields!TransactionAmount.Value))
Now I need to have different total amounts based upon 'payment type'. The payment_types are either 'check', or 'credit' for credit card. Thus can you show me how to change the code I just listed to sum the amount depending upon the payment type?You may wish to follow this thread that is exploring a similar question.
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/12e2cdf4-1fd7-4f2a-ba12-ff5c4ec01eeb/sum-values-based-on-condition-in-ssrs?forum=sqlreportingservices
To do this in an SSRS expression just insert an IIf:
=Sum(IIf(Fields!payment_type.Value = "check",cdec(Fields!TransactionAmount.Value),0))
=Sum(IIf(Fields!payment_type.Value = "credit",cdec(Fields!TransactionAmount.Value),0))
In the other thread you will see that sometimes it makes sense to do this kind of work in the dataset since dataset queries run on the datasource and often those systems are robust servers that can crunch and return data very quickly.
"You will find a fortune, though it will not be the one you seek." -
Blind Seer, O Brother Where Art Thou
Please Mark posts as answers or helpful so that others may find the fortune they seek. -
Are there any MDX gurus who can help me?
I am trying to produce an MDX query that generates a ranked result set, within this I am trying to get two levels of ranking based on Net Sales, firstly the ranking within the overall set, and secondly a ranking partitioned by an attribute dimension (the equivalent of RANK () OVER (PARTITION BY ...) in SQL Server), with the final result set sorted alphabetically by the attribute name and secondly by Net Sales. So far I have got the sorting and the overall ranking to work but not the partitioned rank. Any solution will need to be fast as the base dimension has 100K members.
My current MDX looks like this:
WITH
SET [Divisions] AS '[AttributeContract].[Att_CC01].Children'
SET [ContractsByDiv] AS
'GENERATE(
ORDER(
[AttributeContract].[Att_CC01].Children,
AttributeContract.CurrentMember.[MEMBER_NAME],
BASC
CROSSJOIN(
AttributeContract.CurrentMember
ORDER(
NonEmptySubset(
UDA([Entity].[Entity Contract Reporting], "Contract")
[Net Sales],
BDESC
MEMBER [Account].[Overall Rank] AS 'Rank([ContractsByDiv].CurrentTuple,[ContractsByDiv],[Net Sales])'
MEMBER [Account].[Rank In Div] AS '1'
SELECT
[Net Sales]
,[Overall Rank]
,[Rank In Div]
} ON COLUMNS,
[ContractsByDiv]
} ON ROWS
FROM HCREPRT2.Analysis
WHERE
[Year].[FY13],
[Period].[BegBalance],
[ISBN Type].[Total ISBN Type],
[Lifecycle].[Front List],
[Scenario].[DPG_Budget],
[Market].[Total Market],
[Version].[Working],
[Sales Channel].[Total Sales Channel]
Any suggestions as to how to do this or whether it is possible?
Regards,
Gavin
Edited by: GavinH on 07-Mar-2012 02:57This was the solution I came up with:
The following query returns a result set with the the data ranked across the overall set and with a ranking partioned by division:
WITH
SET [Divisions] AS 'ORDER([AttributeContract].[Att_CC01].Children,AttributeContract.CurrentMember.[MEMBER_NAME],BASC)'
SET [EntitySet] AS 'ORDER(NonEmptySubset(UDA([Entity].[Entity Contract Reporting], "Contract")),[Net Sales],BDESC)'
SET [ContractsByDiv] AS
'GENERATE(
[Divisions],
CROSSJOIN(
AttributeContract.CurrentMember
NonEmptySubset([EntitySet])
-- Rank in whole data set
MEMBER [Account].[Overall Rank] AS 'Rank([ContractsByDiv].CurrentTuple,[ContractsByDiv],[Net Sales])'
-- Ranking in division
MEMBER [Account].[Rank In Div] AS
'Rank(
([AttributeContract].CurrentMember,[Entity].[Entity Contract Reporting].CurrentMember),
CROSSJOIN(
AttributeContract.CurrentMember
NonEmptySubset([EntitySet])
[Net Sales]
-- Rownumber
MEMBER [Account].[RowNumber] AS 'RANK([ContractsByDiv].CurrentTuple,[ContractsByDiv],1,ORDINALRANK)'
SELECT
[Net Sales]
,[Overall Rank]
,[Rank In Div]
,[RowNumber]
} ON COLUMNS,
[ContractsByDiv]
} ON ROWS
FROM HCREPRT2.Analysis
WHERE
[Year].[FY13],
[Period].[BegBalance],
[ISBN Type].[Total ISBN Type],
[Lifecycle].[Front List],
[Scenario].[DPG_Budget],
[Market].[Total Market],
[Version].[Working],
[Sales Channel].[Total Sales Channel]
The key was to use the cross join portion of the generate statement used to create the overall set as the set for the intra divisional ranking. -
Hi,
I am using OWB V9i. I need to implement an sql statement in a mapping.The statement is
CASE WHEN (tr_dt=lead(tr_dt) OVER(PARTITION BY ID ORDER BY ID,tr_dt))
THEN lead(ef_dt) OVER(PARTITION BY ID ORDER BY ID,tr_dt)
ELSE tr_dt
END
I am not able to put the case statement in an expression as it has OVER PARTITION BY which the expression operator is not accepting. Is there any way i can implement the same in the mapping without using a table function or any other procedure???
Regards
BharathOWB's support for analytics has always been pretty sparse. They did release a doc that showed a way to build some analytics using various workarounds here:
http://www.oracle.com/technology/sample_code/products/warehouse/files/analyticfunctions.pdf
However my approach has always been to tend towards simplicity. A convoluted "workaround"mapping is harder to tune, troubleshoot, or maintain, and I always worry about how OWB will handle such workarounds over subsequent release upgrades. So, for anything not clearly natively supported by OWB - I build a view with the analytic and use that as my source.
Mike
Maybe you are looking for
-
I have use three free apple Id and now when I am creating a fourth time it's saying that it is the maximum. What must I do to create a new apple id. Plz help
-
In ABAP How to locate an Input file from a Directory during run time
I'm loading data from a flat file(text file) into SAP thru BDC programs. All my input files are present in Application server.How to locate an Input file in a directory during run time to process BDC programs programmatically. Are there any in-built
-
i've downloaded the Pl/SQL XML parser demo - xslsample / domsample - followed the guide , etc but I'm getting .... BEGIN xslsample ('/export/home/oracle/plmx/sample','family.xml','iden.xsl','family.out','errors.txt'); END; ERROR at line 1: ORA-29516:
-
Can't change names of files in Finder after Leopard upgrade
OK, I'm sure this is an easy fix, but I haven't found this precise situation looking around. Hopefully someone can point me to exactly the right utility. I had Tiger, then upgraded to Leopard, then had some of the problems reported elsewhere on this
-
Help with moving between custom screens in a Standard Transaction
All, I'm working with a standard transaction, but in this transaction, the I'm having 2 tabs of customized screens. In each of the screen, I have 1 mandatory fields to be filled. If the user only fill in the mandatory field of the first screen and cl