Distinct & order by
Hi,
I have a data in this format.
Name Type ctg Id subctg Id
AA Long 1 1
AA Long 1 1
pfAA Long 1 3
P1+ Short 1 1
Now I want distinct name from a materilazed view in the following order
Order by clause should be Type,Ctg Id,SubctgId
Output:
AA
PfAA
P1+
I have already ready previous threads on this but sorry i didn't get it.
Pls help.
Thanks
Regards
Anant
ok,
you might start with this:
CREATE OR REPLACE FUNCTION ftest(
pid IN NUMBER,
psubid IN NUMBER
RETURN VARCHAR2 IS
RESULT VARCHAR2(4000) := NULL;
BEGIN
FOR i IN (SELECT MAX(NAME) NAME
FROM <yourtable>
WHERE ID = pid
AND sub_id = psubid
GROUP BY NAME,
ctg_id,
subctg_id
ORDER BY ctg_id,
subctg_id) LOOP
IF RESULT IS NULL THEN
RESULT := i.NAME;
ELSE
RESULT := RESULT
|| '/'
|| i.NAME;
END IF;
END LOOP;
RETURN RESULT;
END;
/will gives:
select ftest(100,12) from dual
AA Long/FAAA Mid/P1+ Short/PFAA Long/AA(so) LongReplace the <yourtable> with your table name.
you can change the way the rows are retrieved (the order, uniqueness and so on)
But as said before, your can obtain this result without creating a function (only with SQL) but it will be probably not be the easiest for your to understand...
Edited by: user11268895 on Aug 17, 2010 11:36 AM
Similar Messages
-
Using distinct with an Order by
Hi all,
I'm not an expert SQL coder and I've got stuck with the following issue.
I have a table named Workorder which contains a set of orders. Orders with status_id = 2 contain an error and this need to be re-submitted:
[ ID ] [WO_ID] [STATUS_ID]
1 10 2
2 10 1
3 20 2
So apparentely it seems very simple, however when orders are re-submitted things get complicated.
In the above query I need to pickup -just- the following row:
[ ID ] [WO_ID] [STATUS_ID]
3 20 2
The following row needs to be excluded from the list:
[ ID ] [WO_ID] [STATUS_ID]
1 10 2
Because the WO_ID has been later re-submitted successufully:
[ ID ] [WO_ID] [STATUS_ID]
2 10 1
So I need to pickup all workorders with a distinct on WO_ID ordered by ID desc, so that the distinct row contains just the highest ID (the latest order re-submitted).
I've tried in several ways, however I wasn't able to mix distinct + order by.
Maybe it can be done also in some other simpler ways ?
Thanks a lot
FrankSo, if the last ID for each WO_ID has STATUS_ID=2, that row needs to in the output.
But if the last ID has a different STATUS_ID, then that WO_ID is not to be in the output at all?
Perhaps this could work for you:
select
max(id) as id,
wo_id,
max(status_id) keep (dense_rank last order by id) as status_id
from workorder
group by wo_id
having max(status_id) keep (dense_rank last order by id) = 2
order by wo_idEdit:
Or an alternative using analytic functions:
select
id,
wo_id,
status_id
from (
select
id,
wo_id,
status_id,
last_value(status_id) over (
partition by wo_id
order by id
rows between unbounded preceding and unbounded following
) as last_status
from workorder
where last_status = 2If your workorder table actually contains several other columns you wish to select along with the id and status, then the analytic way can be much easier than a bunch of "keep" expressions ;-)
Edited by: Kim Berg Hansen on Nov 29, 2011 12:22 PM -
Need Help With SQL GROUP BY and DISTINCT
I am working on a project and need to display the total of each order based on the order id. For instance I want to display the order id, customer id, order date, and then the extension price (ol_quantity * inv_price).
I would then like a total displayed for order # 1 and then move on to order #2.
Here is my SQL code :
SELECT DISTINCT orders.o_id, customer.c_id, inv_price * ol_quantity
FROM orders, customer, inventory, order_line
GROUP BY orders.o_id, customer.c_id, inv_price, ol_quantity
ORDER BY orders.o_id;
When my code is run it displays the order id, customer id and inv_price * quantity (extension price) but no order total for the order number and a new group is not started when a new order number is started....they are all clumped together.
Any help is greatly appreciated!!Hi,
user12036843 wrote:
I am working on a project and need to display the total of each order based on the order id. For instance I want to display the order id, customer id, order date, and then the extension price (ol_quantity * inv_price).
I would then like a total displayed for order # 1 and then move on to order #2.
Here is my SQL code :
SELECT DISTINCT orders.o_id, customer.c_id, inv_price * ol_quantity
FROM orders, customer, inventory, order_line
GROUP BY orders.o_id, customer.c_id, inv_price, ol_quantity
ORDER BY orders.o_id;
When my code is run it displays the order id, customer id and inv_price * quantity (extension price) but no order total for the order number and a new group is not started when a new order number is started....they are all clumped together.
Any help is greatly appreciated!!Sorry, it's unclear what you want.
Whenever you post a question, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and the results you want from that data.
Explain, using specific examples, how you get those results from that data.
Always say what version of Oracle you're using.
Do you want the output to contain one row for each row in the table, plus an extra row for each distinct order, showing something about the order as a whole (e.g., total inv_price or average extension_price)? If so, you need GROUP BY ROLLUP or GROUP BY GROUPING SETS .
If you want one row of output for each row of the table, but you want to include something that reflects the group as a whole (again, e.g, total inv_prive or average extension_pcie), then you can us analytic functions. (Most of the aggregate functions, such as SUM and AVG have analytic counterparts that can get the same results without collapsing the result set down to one row per group.)
Here's an example of how to use GROUP BY GROUPING SETS.
Way we're interested in employees' salary and commission from the scott.emp table:
SELECT deptno
, ename
, sal
, comm
FROM scott.emp
ORDER BY deptno
, ename
;Output:
` DEPTNO ENAME SAL COMM
10 CLARK 2450
10 KING 5000
10 MILLER 1300
20 ADAMS 1100
20 FORD 3000
20 JONES 2975
20 SCOTT 3000
20 SMITH 800
30 ALLEN 1600 300
30 BLAKE 2850
30 JAMES 950
30 MARTIN 1250 1400
30 TURNER 1500 0
30 WARD 1250 500Now say we want to add the total income (sal + comm, or just sal if there is no comm) to each row, and also to add a row for each department showing the total sal, comm and income in that department, like this:
` DEPTNO ENAME SAL COMM INCOME
10 CLARK 2450 2450
10 KING 5000 5000
10 MILLER 1300 1300
10 8750 8750
20 ADAMS 1100 1100
20 FORD 3000 3000
20 JONES 2975 2975
20 SCOTT 3000 3000
20 SMITH 800 800
20 10875 10875
30 ALLEN 1600 300 1900
30 BLAKE 2850 2850
30 JAMES 950 950
30 MARTIN 1250 1400 2650
30 TURNER 1500 0 1500
30 WARD 1250 500 1750
30 9400 2200 11600(This relies on the fact that ename is unique.) Getting those results is pretty easy, using GROUPING SETS:
SELECT deptno
, ename
, SUM (sal) AS sal
, SUM (comm) AS comm
, SUM ( sal
+ NVL (comm, 0)
) AS income
FROM scott.emp
GROUP BY GROUPING SETS ( (deptno)
, (deptno, ename)
ORDER BY deptno
, ename
;Notice that we're displaying SUM (sal) on each row. Most of the rows in the output are "groups" consisting of only one row from the table, so the SUM (sa) for that goup will be the sal for the one row in the group.
Edited by: Frank Kulash on Nov 23, 2011 2:03 PM
Added GROUPING SET example -
Querying dba_constraints, I might finish with an 'order by constraint_type'. But this now means that unique constraints are listed after foreign keys because 'R' sorts before 'U'. If I'm running the query to generate the SQL to re-create the constraints, I'll get a lot of failures because the foreign keys are supposed to reference primary or uniquely-constrained columns, and the unique constraints won't have been created yet. It's no good me ordering by constraint_type desc, either, because then I'll be trying to create foreign keys before the primary keys get created, because 'R' would sort before 'P'. What I really need is all the primary constraints, then all the uniques and all the foreign keys bringing up the rear.
So my question: is there a way of ordering by a column in an arbitrary, user-defined way? Where you say, for example, "order by constraint_type ('P','U','C','R')".
A bit like list partitioning, where you get to define what "constrains" a record to a partitcular partition, only this time, you get to define your ordering sequence.
As another example, I want to sort the EMP table in department number order, but the ordering I want is "20, then 10, then 40 and then 30", for whatever weird business reason you might think up.
Do-able in a simple (or not-so simple) query? I can see how four separate union queries could do it... am wondering if there's anything more elegant and that could extend easily to lots more than 4 distinct ordering values.Decode the constraint type and order by the decoded column. In SQLPlus, you can even NOPRINT the ordering column.
SQL> create table hkc_test_90 (table_name varchar2(30), col_name varchar2(30), constraint_type varchar2(1));
Table created.
SQL> insert into hkc_test_90 values ('T_A','C_1','P');
1 row created.
SQL> insert into hkc_test_90 values ('T_A','C_3','U');
1 row created.
SQL> insert into hkc_test_90 values ('T_B','C_1','P');
1 row created.
SQL> insert into hkc_test_90 values ('T_B','C_2','R');
1 row created.
SQL> insert into hkc_test_90 values ('T_C','C_1','P');
1 row created.
SQL> insert into hkc_test_90 values ('T_C','C_4','R');
1 row created.
SQL> commit;
Commit complete.
SQL>
SQL> select table_name, col_name, constraint_type, decode(constraint_type,'P',1,'U',2,'C',3,'R',4) ctype_no
2 from hkc_test_90
3 order by ctype_no, table_name;
TABLE_NAME COL_NAME C CTYPE_NO
T_A C_1 P 1
T_B C_1 P 1
T_C C_1 P 1
T_A C_3 U 2
T_B C_2 R 4
T_C C_4 R 4
6 rows selected.
SQL> col ctype_no noprint
SQL> select table_name, col_name, constraint_type, decode(constraint_type,'P',1,'U',2,'C',3,'R',4) ctype_no
2 from hkc_test_90
3 order by ctype_no, table_name;
TABLE_NAME COL_NAME C
T_A C_1 P
T_B C_1 P
T_C C_1 P
T_A C_3 U
T_B C_2 R
T_C C_4 R
6 rows selected.
SQL>
Hemant K Chitale -
Calculating count of orders using virtual key figures
Hi All,
In my report, i need a counter for the number of distinct orders.
1ROWCOUNT didnt work for me as i want the count of distinct orders alone.
I am planning to use virtual key figure for this..
However, i donno how to code this in ZXRSRU02 and ZXRSRZZZ.
Any help on this would be great!!
Thanks!
- Arun KKShana,
I dont understand your question.
I'll give an eg.
this is how the cube is.
Order | Desc | Location
101 | 'X' | loc01
101 | 'X' | loc02
102 | 'Y' | loc01
103 | 'Z' | loc01
102 | 'Y' | loc02
in the report, i need the o/p to be.
Order | Desc | count
101 | 'X' | 1
102 | 'Y' | 1
103 | 'Z' | 1
i cant use 1rowcount as that counts each row and not the service orders.
Hope this answers your question.
Please let me know if there is a solution for this.
Thanks!
~ Arun KK -
Distinct in one particular column
Hi Friends I am going to select orderid,date from one table but i want to display only distinct orderid and its corresponding date.
THANKS IN ADVANCEDid you try my above code?
Distinct Order id with latest date? The you may choose ORDER BY sdate desc else with asc.
I think the above would help you to get what you are looking.
SelectOrderid,yourdatecolumn From
Select *,
Row_Number()over(partition by Orderid Order by yourdatecolumn desc) Rn
From CART
)A
Where rn=1 -
How to monitor cube usage in order to add more aggregations to speed up performance
hi all:
We have finally deployed our first Enterprise level cube to production and fact table contains roughly around 150M records.
We also created a measure group for distinct order purpose and works fine for us. Now, we realized that the cube is responding a tad slow when users drag order count to their excel ...
During design phase, I created aggregation based on over all performance ( when 20% achieved, it stopped). What I want to do now is below:
1. I want to know the usage pattern when users are navigating this cube
2. once I know the pattern, how can I add more aggregations based on that?
thanks
--Currently using Reporting Service 2000; Visual Studio .NET 2003; Visual Source Safe SSIS 2008 SSAS 2008, SVN --Hello,
Turn on the "OlapQueryLog" to log to a database table, this results can be used for the "Usage-Based Optimization Wizard".
See Configuring the Analysis Services Query Log +
Based Optimization Wizard F1 Help +
Aggregations and Aggregation Designs
Olaf Helper
[ Blog] [ Xing] [ MVP] -
I need some help with a query that I need to use in order to create a view.
It's fairly complicated, at least for me.
Here is a short summary of the problem:
There is a table involved called salesperson.
This table has a four digit salespersonid, lastname, firstname, hiredate, and supervisor columns.
The supervisor column holds the four digit salespersonid of the supervisor of that particular sales person.
This column is null if that salesperson is the supervisor.
Now I need to generate a view that summarizes book sales by salesperson and shipping state.
7 columns are required.
Salespersonid
Sales person Name
State (based on shipstate)
Total number of orders
total amount of sales
Total profit
Last name of person's supervisor.
It is that last one that is giving me fits.
I don't know how to get the supervisor last name in the output.
Also, if the salesperson is the supervisor (i.e. supervisor column is null) I need to display (none) there. It can't be blank.
Here is what I have so far:
SELECT s.salespersonid AS ID, s.lastname || ', ' || s.firstname AS salesperson, shipstate,
COUNT(DISTINCT order#) AS "TOTAL ORDERS", SUM(retail * quantity) AS "GROSS SALES",
SUM((retail - cost) * quantity) AS "PROFIT"
FROM salesperson s LEFT JOIN orders o ON s.salespersonid = o.salespersonid
LEFT JOIN orderitems oi ON o.order# = oi.order#
LEFT JOIN books b ON oi.isbn = b.isbn
GROUP BY s.salespersonid, s.lastname || ', ' || s.firstname, shipstateIt seems to me that I have to use a self join but my brain is cooked, and I can't seem to figure this out.
I have scripts here that would generate the tables and data I am using.
It's a small database. (If anyone is familiar with Oracle 10g SQL by Joan Casteel it is the JustLeeBooks database used throughout that book)
I don't really want to post these scripts here. It would make for quite a long post.
There are seven of them to get the data consistent with what I am using here.
If someone is willing to spend some time helping me, I could e-mail them the scripts.
They are the script that sets up the initial database and then 6 more scripts I have written to get to this point.
They kind of build on one another.
Send me a private message if you are willing to do that.
We could then bring the discussion back here if that is to your liking.
Any takers?
Maybe someone can help without those scripts?Hi..
If i understood you need this query can help you..
SELECT s.salespersonid AS ID, s.lastname || ', ' || s.firstname AS salesperson, shipstate,
COUNT(DISTINCT order#) AS "TOTAL ORDERS", SUM(retail * quantity) AS "GROSS SALES",
SUM((retail - cost) * quantity) AS "PROFIT",
nvl(sup.lastname || ', ' || sup.firstname,'none') AS supervisor
FROM salesperson s LEFT JOIN orders o ON s.salespersonid = o.salespersonid
LEFT JOIN orderitems oi ON o.order# = oi.order#
LEFT JOIN books b ON oi.isbn = b.isbn
LEFT JOIN salesperson sup ON s.supervisorid = sup.salespersonid
GROUP BY s.salespersonid, s.lastname || ', ' || s.firstname, shipstate, nvl(sup.lastname || ', ' || sup.firstname,'none') Not Tested.
Tell me if there is that you need !!! -
Pl/sql block updating orderId, itemID
lol here i am again!
This time its like this:
i have a table (orderId, itemId, CustomerId, productId, quantity, start_date, end_date, oldRef)
here are some of the values:
2477, 1, 201, 111, 1,19-MAR-93,14-APR-93
2477,2,201,112,1,19-MAR-93,14-APR-93
2478,1,201,113,1,19-MAR-93,14-APR-93
2478,2,201,110,19-Mar-93,14-APR-93
Now as you can see that order_Id is different however order_date and ship_date both match. Now what i want to do is to give them a new orderId, re-arrange itemId if ship_date and order_date match for each customer so the ex above should come out like this:
1, 1, 201, 111, 1,19-MAR-93,14-APR-93
1,2,201,112,1,19-MAR-93,14-APR-93
1,3,201,113,1,19-MAR-93,14-APR-93
1,4,201,110,19-Mar-93,14-APR-93
I have created a pl/sql block. It has a cursor that loops around each row of table. Then it stores orderdate, shipdate and customerId. it also has a itemId variable and orderDate variable. OrderDate variable takes its value from orderId sequence and itemId is just a number that increments itself.
NOW when orderdate,shipdate&customerId are the same, i just update the itemId, if they differ or customer_id changes i get a new order_id, update the variables (orderdate,shipdate,customerid,itemId) but for some reason i dont think it is working!!
DECLARE
cursor c1 is
SELECT
FROM
ph2_item
order by
customer_id,
ship_date,
order_date
for update;
new_order_id number(8,0) := 0;
new_item_id number(4,0) := 1;
temp_odate date := '11-JUN-08';
temp_sdate date:= '11-JUN-08';
temp_cId number(8,0) := 1;
BEGIN
FOR rec in c1 LOOP
IF rec.customer_id = temp_cId THEN
IF (rec.order_date <> temp_odate OR
rec.ship_date <> temp_sdate) THEN
new_item_id:= 1;
SELECT orderid.nextVal into new_order_id from dual;
temp_odate :=rec.order_date;
temp_sdate :=rec.ship_date;
END IF;
ELSE
new_item_id:= 1;
SELECT orderid.nextVal into new_order_id from dual;
temp_cid := rec.customer_id;
temp_odate :=rec.order_date;
temp_sdate :=rec.ship_date;
END IF;
update ph2_item
set order_id = new_order_id, item_id = new_item_id
where current of c1;
new_item_id := new_item_id + 1;
END LOOP;
END;
commit;PS> this is not a real life database and just a college assignment!
just corrected a mistake in one of the example code i posted
Message was edited by:
user646562well it does seem to give the right results ie. orderId is changed and itemId is rearranged! however the college has an online marker and when i try to submit the code, it says that the max(order_id) of the resulting table (ph2_item) is wrong, the sum(item_id) is wrong and the no of distinct orders is wrong.. this means i am either consolidating orders whne i shouldnt, and this in turns make my item_id wrong..
also there is one more criteria i should have mentioned but i forgot and that is even if the order_date and ship_date is the same as another order, we will only consolidate them if the customer in question has multiple sites.
here is the updated pl/sql block taking into account this criteria (using if/else statement)
DECLARE
cursor c1 is
SELECT
FROM
ph2_item
order by
order_date,
customer_id
for update;
new_order_id number(8,0) := 0;
new_item_id number(4,0) := 1;
temp_odate date := '11-JUN-08';
temp_sdate date:= '11-JUN-08';
temp_cId number(8,0) := 1;
totalSites number(2,0);
BEGIN
FOR rec in c1 LOOP
select site_count into totalsites from customer_sites where customer_id = rec.customer_id;
--dbms_output.put_line(rec.customer_id ||' ' || totalsites);
if totalsites > 1 THEN
IF rec.customer_id = temp_cId THEN
IF (rec.ship_date <> temp_sdate AND rec.order_date <> temp_odate) AND rec.ship_date is null THEN
new_item_id:= 1;
SELECT orderid.nextVal into new_order_id from dual;
temp_odate :=rec.order_date;
--temp_sdate :=rec.ship_date;
END IF;
ELSE
new_item_id:= 1;
SELECT orderid.nextVal into new_order_id from dual;
temp_cid := rec.customer_id;
temp_odate :=rec.order_date;
--temp_sdate :=rec.ship_date;
END IF;
ELSE
new_item_id:= 1;
SELECT orderid.nextVal into new_order_id from dual;
temp_cid := rec.customer_id;
temp_odate :=rec.order_date;
--temp_sdate :=rec.ship_date;
END IF;
update ph2_item
set order_id = new_order_id, item_id = new_item_id
where current of c1;
new_item_id := new_item_id + 1;
END LOOP;
END; -
Performance Tuning in case of Database Access
Hi,
I am using following code...database access is huge for this code...pls help me out to make database access minimum. I am using 3 internal tables.
select partner1 partner2 into (mtab-busi_part, mtab-BUT051_PART)
from but051.
Select name_first name_last PARTNER_GUID into (mtab-bp_first, mtab-bp_last, MTAB-R_PARTNER_GUID)
From but000 where partner = mtab-busi_part.
*MTAB-OBJECT_ID = ITAB-OBJECT_ID.
append mtab.
endselect.
ENDSELECT.
*ENDLOOP.
loop at mtab.
CONCATENATE mtab-bp_FIRST mtab-bp_LAST INTO mTAB-bp_full
separated BY SPACE.
modify mtab.
endloop.
loop at mtab.
if mtab-bp_full = ' '.
select name_org1 into (mtab-bp_full)
from but000 where partner = mtab-busi_part.
append mtab.
endselect.
endif.
modify mtab.
clear mtab.
endloop.
SELECT OBJECT_ID GUID INTO (NTAB-object_id, Ntab-guid)
FROM CRMD_ORDERADM_H
for all entries in itab
where process_type = '1001' and object_id in o_id.
select single date_1 date_2 from crmv_item_index into (ntab-date_1, ntab-date_2 )
where object_id = ntab-object_id.
endselect.
Select partner_no partner_fct into (Ntab-partner_guid, Ntab-partner_fct)
from bbp_pdview_bup where guid_hi = Ntab-guid .
*and partner_fct <> '00000015'
Select partner name_org1 into (Ntab-partner_no2, Ntab-others)
from but000 where partner_guid = Ntab-partner_guid.
if sy-subrc = 0.
SELECT SINGLE DESCRIPTION FROM CDBC_PARTNER_FT INTO NTAB-DESC
WHERE PARTNER_FCT = NTAB-PARTNER_FCT AND SPRAS = 'EN'.
endif.
SELECT PAFKT ABTNR PAAUTH
FROM BUT051 INTO corresponding fields of nTAB
WHERE PARTNER2 = ntab-partner_no2 .
if sy-subrc = 0.
SELECT single BEZ30 FROM TB913
INTO CORRESPONDING FIELDS OF nTAB
WHERE PAFKT = nTAB-PAFKT AND SPRAS = 'E'.
endif.
if sy-subrc = 0.
SELECT single BEZ20 FROM TB915
INTO CORRESPONDING FIELDS OF nTAB
WHERE PAAUTH = nTAB-PAAUTH AND SPRAS = 'E'.
endif.
*endselect.
if sy-subrc = 0.
SELECT single BEZ20 FROM TB911
INTO (nTAB-BEZ2)
WHERE ABTNR = nTAB-ABTNR AND SPRAS = 'E'.
endif.
endselect.
APPEND NTAB.
*clear ntab.
*ENDSELECT.
ENDSELECT.
*clear ntab.
ENDSELECT.
ENDSELECT.
loop at ntab.
if ntab-others = ' '.
select name_first name_last into (ntab-first_name1, ntab-last_name1)
from but000 where partner = ntab-partner_no2.
endselect.
CONCATENATE ntab-FIRST_NAME1 ntab-LAST_NAME1 INTO nTAB-others
separated BY SPACE.
endif.
modify ntab.
clear ntab.
endloop.
SORT NTAB BY GUID.
SELECT OBJECT_ID GUID INTO (KTAB-object_id, Ktab-guid)
FROM CRMD_ORDERADM_H
for all entries in itab
where process_type = '1001' and object_id in o_id.
Select partner_no into (Ktab-partner_no1)
From crmd_order_index where header = Ktab-guid and pft_8 = 'X' and object_type = 'BUS2000126'.
*endselect.
Select name_first name_last into (Ktab-first_name, Ktab-last_name)
From but000 where partner = Ktab-partner_no1.
*endselect.
APPEND KTAB.
ENDSELECT.
ENDSELECT.
ENDSELECT.
loop at Ktab.
CONCATENATE Ktab-FIRST_NAME Ktab-LAST_NAME INTO KTAB-RESP_EMPLOYEE
separated BY SPACE.
MODIFY KTAB.
clear Ktab.
endloop.
loop at Ktab.
if Ktab-RESP_EMPLOYEE = ' '.
select name_ORG1 into (Ktab-RESP_EMPLOYEE)
from but000 where partner = Ktab-partner_no1.
endselect.
endif.
modify Ktab.
clear Ktab.
endloop.
SELECT OBJECT_ID GUID INTO (itab-object_id, itab-guid)
FROM CRMD_ORDERADM_H
where process_type = '1001' and object_id in o_id.
append itab.
endselect.
LOOP AT iTAB.
LOOP AT NTAB .
IF NTAB-object_id = iTAB-object_id .
itab-date_1 = ntab-date_1.
ITAB-DESC = NTAB-DESC.
itab-partner_no2 = NTab-partner_no2.
itab-partner_fct = ntab-partner_fct.
itab-bez30 = ntab-bez30.
itab-bez20 = ntab-bez20.
itab-bez2 = ntab-bez2.
itab-others = ntab-others.
INSERT lines of nTAB INTO ITAB.
modify itab.
CLEAR ITAB.
delete itab where object_id = ' ' and partner_no2 = ' '.
ENDIF.
endloop.
endloop.
sort itab by OBJECT_ID descending PARTNER_NO2 .
delete adjacent duplicates from itab comparing partner_no2 object_id.
sort itab by OBJECT_ID descending PARTNER_NO2 .
loop at iTab where partner_fct = '00000015'.
LOOP AT mTAB WHERE BUT051_PART = iTAB-partner_no2 .
itab-busi_part = mtab-busi_part.
itab-bp_full = mtab-bp_full.
ITAB-R_PARTNER_GUID = MTAB-R_PARTNER_GUID.
INSERT LINES OF mTAB INTO iTAB.
modify itab transporting busi_part bp_full r_partner_guid.
endloop.
endloop.
sort itab by busi_part descending partner_no2.
delete itab where object_id = ' '.
loop at ITab.
LOOP AT KTAB.
IF KTAB-GUID = ITAB-GUID.
move Ktab-partner_no1 to itab-partner_no1.
move Ktab-R_partner_GUID to itab-R_partner_GUID.
move Ktab-RESP_EMPLOYEE to itab-RESP_EMPLOYEE.
modify itab.
ENDIF.
endloop.
endloop.Hi
i will give you some tips to reduce the daya base load please apply that
<b>Tips and Tricks</b>
Optimizing the load of the database
Using table buffering
Using buffered tables improves the performance considerably. Note that in some cases a statement can not be used with a buffered table, so when using these statements the buffer will be bypassed. These statements are:
Select DISTINCT
ORDER BY / GROUP BY / HAVING clause
Any WHERE clause that contains a sub query or IS NULL expression
JOIN s
A SELECT... FOR UPDATE
If you wan t to explicitly bypass the buffer, use the BYPASS BUFFER addition to the SELECT clause.
Optimizing the load of the database
2. Use the ABAP SORT Clause Instead of ORDER BY
The ORDER BY clause is executed on the database server while the ABAP SORT statement is executed on the application server. The database server will usually be the bottleneck, so sometimes it is better to move the sort from the database server to the application server.
If you are not sorting by the primary key ( E.g. using the ORDER BY PRIMARY key statement) but are sorting by another key, it could be better to use the ABAP SORT statement to sort the data in an internal table. Note however that for very large result sets it might not be a feasible solution and you would want to let the database server sort it.
Optimizing the load of the database
3. Avoid the SELECT DISTINCT Statement
As with the ORDER BY clause it could be better to avoid using SELECT DISTINCT, if some of the fields are not part of an index. Instead use ABAP SORT + DELETE ADJACENT DUPLICATES on an internal table, to delete duplicate rows.
Additional Info
Use of CONTEXT can highly optimize the code.
Context can be created using Context Builder (SE33)
Context advantages: - no double fetch by DEMAND: 1. fetch, 2. get from buffer - more performance (best SELECT-statement) - better survey of code
Use of PARALLEL CURSOR increases the Performance to a great extent.
INDEXES help to speed up selection from the database. The primary index is always created automatically in the SAP System. It consists of the primary key fields of the database table. If you cannot use the primary index to determine a selection result (for example, WHERE condition may not contain any primary index fields), you can create a secondary index.
Optimal number of indexes for a table You should not create more than five secondary indexes for any one table because:
Whenever you change table fields that occur in the index, the index itself is also updated.
The amount of data increases.
The optimizer has too many chances to make mistakes by using the 'wrong' index.
If you are using more than one index for a database table, ensure that they do not overlap.
reward if useful -
Regarding performance of report
hi SDNs,
my report is running for more than 30 min and going dumb.
so i am increasing the performance by considering every thing..
putting indexes in select stmts .
while reading ( READ TABLE ) using binary search.
sorting before reading.
thing is still showing, some poor performance..
what to consider inorder to increase the perofrmance?
and here report has to extract huge data ( min 50,000 records )
shall i use HASHED OR SORTED ? how to use these??
i am using STANDARD now ??
pls help me .,
Thanking you,
ramuhi,
pls go thru this. def this will help
Performance tuning for Data Selection Statement
For all entries
The for all entries creates a where clause, where all the entries in the driver table are combined with OR. If the number of
entries in the driver table is larger than rsdb/max_blocking_factor, several similar SQL statements are executed to limit the
length of the WHERE clause.
The plus
Large amount of data
Mixing processing and reading of data
Fast internal reprocessing of data
Fast
The Minus
Difficult to program/understand
Memory could be critical (use FREE or PACKAGE size)
Some steps that might make FOR ALL ENTRIES more efficient:
Removing duplicates from the the driver table
Sorting the driver table
If possible, convert the data in the driver table to ranges so a BETWEEN statement is used instead of and OR statement:
FOR ALL ENTRIES IN i_tab
WHERE mykey >= i_tab-low and
mykey <= i_tab-high.
Nested selects
The plus:
Small amount of data
Mixing processing and reading of data
Easy to code - and understand
The minus:
Large amount of data
when mixed processing isnt needed
Performance killer no. 1
Select using JOINS
The plus
Very large amount of data
Similar to Nested selects - when the accesses are planned by the programmer
In some cases the fastest
Not so memory critical
The minus
Very difficult to program/understand
Mixing processing and reading of data not possible
Use the selection criteria
SELECT * FROM SBOOK.
CHECK: SBOOK-CARRID = 'LH' AND
SBOOK-CONNID = '0400'.
ENDSELECT.
SELECT * FROM SBOOK
WHERE CARRID = 'LH' AND
CONNID = '0400'.
ENDSELECT.
Use the aggregated functions
C4A = '000'.
SELECT * FROM T100
WHERE SPRSL = 'D' AND
ARBGB = '00'.
CHECK: T100-MSGNR > C4A.
C4A = T100-MSGNR.
ENDSELECT.
SELECT MAX( MSGNR ) FROM T100 INTO C4A
WHERE SPRSL = 'D' AND
ARBGB = '00'.
Select with view
SELECT * FROM DD01L
WHERE DOMNAME LIKE 'CHAR%'
AND AS4LOCAL = 'A'.
SELECT SINGLE * FROM DD01T
WHERE DOMNAME = DD01L-DOMNAME
AND AS4LOCAL = 'A'
AND AS4VERS = DD01L-AS4VERS
AND DDLANGUAGE = SY-LANGU.
ENDSELECT.
SELECT * FROM DD01V
WHERE DOMNAME LIKE 'CHAR%'
AND DDLANGUAGE = SY-LANGU.
ENDSELECT.
Select with index support
SELECT * FROM T100
WHERE ARBGB = '00'
AND MSGNR = '999'.
ENDSELECT.
SELECT * FROM T002.
SELECT * FROM T100
WHERE SPRSL = T002-SPRAS
AND ARBGB = '00'
AND MSGNR = '999'.
ENDSELECT.
ENDSELECT.
Select Into table
REFRESH X006.
SELECT * FROM T006 INTO X006.
APPEND X006.
ENDSELECT
SELECT * FROM T006 INTO TABLE X006.
Select with selection list
SELECT * FROM DD01L
WHERE DOMNAME LIKE 'CHAR%'
AND AS4LOCAL = 'A'.
ENDSELECT
SELECT DOMNAME FROM DD01L
INTO DD01L-DOMNAME
WHERE DOMNAME LIKE 'CHAR%'
AND AS4LOCAL = 'A'.
ENDSELECT
Key access to multiple lines
LOOP AT TAB.
CHECK TAB-K = KVAL.
ENDLOOP.
LOOP AT TAB WHERE K = KVAL.
ENDLOOP.
Copying internal tables
REFRESH TAB_DEST.
LOOP AT TAB_SRC INTO TAB_DEST.
APPEND TAB_DEST.
ENDLOOP.
TAB_DEST[] = TAB_SRC[].
Modifying a set of lines
LOOP AT TAB.
IF TAB-FLAG IS INITIAL.
TAB-FLAG = 'X'.
ENDIF.
MODIFY TAB.
ENDLOOP.
TAB-FLAG = 'X'.
MODIFY TAB TRANSPORTING FLAG
WHERE FLAG IS INITIAL.
Deleting a sequence of lines
DO 101 TIMES.
DELETE TAB_DEST INDEX 450.
ENDDO.
DELETE TAB_DEST FROM 450 TO 550.
Linear search vs. binary
READ TABLE TAB WITH KEY K = 'X'.
READ TABLE TAB WITH KEY K = 'X' BINARY SEARCH.
Comparison of internal tables
DESCRIBE TABLE: TAB1 LINES L1,
TAB2 LINES L2.
IF L1 <> L2.
TAB_DIFFERENT = 'X'.
ELSE.
TAB_DIFFERENT = SPACE.
LOOP AT TAB1.
READ TABLE TAB2 INDEX SY-TABIX.
IF TAB1 <> TAB2.
TAB_DIFFERENT = 'X'. EXIT.
ENDIF.
ENDLOOP.
ENDIF.
IF TAB_DIFFERENT = SPACE.
ENDIF.
IF TAB1[] = TAB2[].
ENDIF.
Modify selected components
LOOP AT TAB.
TAB-DATE = SY-DATUM.
MODIFY TAB.
ENDLOOP.
WA-DATE = SY-DATUM.
LOOP AT TAB.
MODIFY TAB FROM WA TRANSPORTING DATE.
ENDLOOP.
Appending two internal tables
LOOP AT TAB_SRC.
APPEND TAB_SRC TO TAB_DEST.
ENDLOOP
APPEND LINES OF TAB_SRC TO TAB_DEST.
Deleting a set of lines
LOOP AT TAB_DEST WHERE K = KVAL.
DELETE TAB_DEST.
ENDLOOP
DELETE TAB_DEST WHERE K = KVAL.
Tools available in SAP to pin-point a performance problem
The runtime analysis (SE30)
SQL Trace (ST05)
Tips and Tricks tool
The performance database
Optimizing the load of the database
Using table buffering
Using buffered tables improves the performance considerably. Note that in some cases a stament can not be used with a buffered table, so when using these staments the buffer will be bypassed. These staments are:
Select DISTINCT
ORDER BY / GROUP BY / HAVING clause
Any WHERE clasuse that contains a subquery or IS NULL expression
JOIN s
A SELECT... FOR UPDATE
If you wnat to explicitly bypass the bufer, use the BYPASS BUFFER addition to the SELECT clause.
Use the ABAP SORT Clause Instead of ORDER BY
The ORDER BY clause is executed on the database server while the ABAP SORT statement is executed on the application server. The datbase server will usually be the bottleneck, so sometimes it is better to move thje sort from the datsbase server to the application server.
If you are not sorting by the primary key ( E.g. using the ORDER BY PRIMARY key statement) but are sorting by another key, it could be better to use the ABAP SORT stament to sort the data in an internal table. Note however that for very large result sets it might not be a feasible solution and you would want to let the datbase server sort it.
Avoid ther SELECT DISTINCT Statement
As with the ORDER BY clause it could be better to avoid using SELECT DISTINCT, if some of the fields are not part of an index. Instead use ABAP SORT + DELETE ADJACENT DUPLICATES on an internal table, to delete duplciate rows.
http://www.erpgenie.com/abap/performance.htm
http://www.thespot4sap.com/Articles/SAPABAPPerformanceTuning_PerformanceAnalysisTools.asp
http://www.sap-img.com/abap/performance-tuning-for-data-selection-statement.htm
for any clarifiaction pls mail me.
pls reward points, if this helped u.
regards,
anversha.
[email protected] -
How to do the multimapping in File to File Scenario
Hi All,
I am doing File to File scenario using Multimapping Concept.pls send the procedure how to do the Massege mapping using Multimapping.
I have a source structure like this.
<order header>
order no
order Description
</order header>
<Orderitem>
matno
description
Qty
UOM
</Orderitem>
i need output text file Like
Ono Oodesc OMatno Odes Oqty OUOM
1 02 123 Oil 2 L
1 02 789 Milk 4 L
How to do the multimapping for this.if any Advanced java functions needed pls send the code.
Thanks
Govindu.Hello Govind,
Make the target str as below
<root>
<Row>
<OrderNo></OrderNo>
<OrderDesc></OrderDesc>
<Matno></Matno>,
<Desc></Desc>
<Qty></Qty>
<UOM></UOM>
</Row>
</root>
The mapping for elements
<Matno>,<Desc>,<Qty>,<UOM> is straight-forward. The node <Row> can be mapped to <OrderItem> node in source. For orderNo and OrderDesc you need to use advanced UDF (with entire queue cached) as below.
public void getOrderNo(String[] a,String[] b,ResultList result, Container container){
/Declare a vector to store unique Order Numbers /Order Desc/
Vector vOno = new Vector();
for (int i = 0;i<a.length;i++){
if (a<i>.equals()ResultList.CC) continue;
/Add distinct Order numbers to the vector/
if(!vOno.contains(a<i>)) vOno.add(a<i>);
int headerCounter = 0;
String value = new String();
value = (String) vOno.get(headerCounter);
for (int j = 0;j<b.length;j++){
/When context changes, move to next order no/
if (b[j].equals()ResultList.CC){
headerCounter++;
value = (String) vOno.get(headerCounter);
continue;
/Repeat the current order number/Order Desc until a context change occurs/
result.addValue(value);
The mapping for OrderNo can be like below:
Pass <Order No> from Header to the UDF as array a[] and <OrderItem> from Item as array b[]. Take the output of the function and make it SplitByValue the result of which can be passed to OrderNo. The context of both < Order No> and <OrderItem> has to be one level higher.
Similar mapping for OrderDesc can be made using the same UDF
I hope that resolves your problem.
Regards
Amit -
Why has CAST(FieldName to float) failed in view but not in SELECT?
I've just solved a problem but I'm still not sure what the problem is!
I have a data (staging) table with all values stored as text. The data is converted to the correct data-type and also aggregated somewhat in a view. A select statement with the conversion works. A select statement with the conversion and aggregation (GROUP
BY) works. Creating a view of the conversion and aggregation works. However, on selecting from the view (e.g. SELECT TOP 1000 * FROM ViewName) it fails saying it cannot convert from varchar to float. There are no visible characters in the field apart from
numbers between 0 and 9, a decimal point and sometimes a leading minus sign (-).
The fix? Cast to money and then cast to float.
The problem? I don't know! What was the problem? Some of the values had up to 10 decimal places. Was that a problem? Was it really an overflow error masquerading as conversion error? The longest strings present were:
-2.609763091
-0.082456066
-0.674010546
-2.563428427
-0.016109637
-0.313600766
-0.104452264
-0.853811384
-0.302529502
-0.000362354
-0.002961949
-0.319269185
-0.001970796
Would really like to know what caused this so I can spot it in future before it happens.
Cheers.
JCEHOne possibility is that the two execution plans are different. The logical order of the way SQL processes the clauses a SELECT query is FROM, ON, OUTER, WHERE, GROUP BY, CUBE | ROLLUP, HAVING, SELECT, DISTINCT, ORDER BY, TOP. (Actually that's
what I learned, now there are some additional things like APPLY, but for our purposes we can ignore them). The important thing to know is that that is the LOGICAL order, but SQL is allowed (and often does) go change that order to anything it wants as
long as it returns the correct result.
So, for example, if your FROM clause a number of rows and some of those rows contain data which would cause a CAST (or anything else) in the SELECT clause to fail, but those rows are eliminated by your WHERE clause. Then SQL could do
FROM, WHERE, SELECT and the query works, or
FROM, SELECT, WHERE and the query fails. And, in general, you cannot control which plan SQL will use.
So, for example, if you have a table named T with two integer columns I and J and some rows in the table have a value of 0 in the column J and you run
SELECT I/J FROM T WHERE J<>0
it might work and you might get a divide by zero error. So one safe way to handle this is to write your query as
SELECT I/(CASE WHEN J <> 0 THEN J ELSE NULL END) WHERE J<>0
Another way would be to create a temp table and write an insert statement that inserted into that temp table only the rows where J<>0 and then do the query from the temp table. Since that is two SQL commands, SQL is forced to do them in order,
it cannot combine them and reorder the processing, that would look like
Create Table #T(I int, J int);
Insert Table #T(I, J)
Select I, J FROM T WHERE J<>0;
Select I/J From #T;
Drop Table #T;
You could try doing the equivalent of one of those to your query and see if that makes the problem go away.
Now I know you are going to ask "Why did the view use to work and it doesn't anymore?" and "Why does using the view and the table return different results". My guess is that you are getting different plans for the view and the table,
why that is, I don't know, it is often difficult to answer that type of question. My best guess for why the view used to work, then you ALTERED it, and then changed it back to the original form and it fails even though it is exactly the same as the old
view that was working is, when you had the old view, then was a cached execution plan that was working. That execution plan might have been created a good while ago. When you ALTERED it, you, of course, got a new plan. Then when you ALTERED
it back to the original form, it no longer had the plan it had been using, so had to create a new one, and this new plan was different than the old one.
Finally, if this is the cause of your problem, then you are not guaranteed that the convert to money, then to float is a permanent fix. If you have column headers which cannot be converted to either money or float, then it could be the convert to money
then to float is enough to get SQL to do the WHERE first, then the SELECT. But there is no guarantee that will be true forever. Changes in your data distribution and release level of SQL might make that version do the select first and then the
where.
Tom -
Promise T3 and port multiplier function
I have a K9A2 Platinum mobo. It has a Promise T3 controller for the ESata ports. I can find no documentation on this controller, so maybe the company who made them went out of business. I am looking for the information about this controller of whether it supports a "port multiplier function" since I am considering buying a MB561US-4S-1 Quad Bay eSATA & USB 2.0 External Enclosure from Icy Dock.
Quote from: Bas on 12-January-11, 05:42:36
Typical.
That is why I say, test it first.
Desktop boards often fail to boot from add-in RAID/SATA/SAS/SCSI cards.
And trust me, it more a rule that it fails.
I would like to find a card before I buy the enclosure, but maybe you are right that I should just buy the enclosure I want and then see if it will work directly with the Promise T3 controller on the K9A2 Platinum mobo, if that is what you are suggesting.
As far as testing a card first, I can not do that until I buy a card and then if it does not work I would need to return it. I do not currently have an add-in card with port multiplier function capability.
My reason for wanting to find out in advance whether the Promise T3 controller will work or not is not only that I do not want to have to wait again if I have to get a card but also that I will normally buy all of my items from New Egg and I do not want to have to pay separate shipping for two distinct orders if I can get everything at once.
One of the pluses of building one's own system is that I should be able to find out the technical details of the mobo's components. But finding out about the Promise T3 controller has proved frustrating. I do have a question about the Promise T3 controller in to MSI support so I hope to get a definitive answer shortly from them. -
SELECT DISTINCT icms_task_assigned.task,icms_task_department.task_department,icms_assigned_to.assigned_to,to_char(icms_task_assigned.target_date,'DD-Mon-YYYY') AS target_date,call_status,icms_task_assigned.remarks,icms_task_assigned.task_id FROM icms_task_assigned LEFT JOIN icms_task_department ON icms_task_department.task_department_id = icms_task_assigned.department LEFT JOIN icms_assigned_to ON icms_assigned_to.assigned_to_id = icms_task_assigned.assigned_to WHERE icms_users.user_id = 1 AND to_char(icms_task_assigned.assigned_date,'YYYY-MM-DD') >= '2006-07-01' AND to_char(icms_task_assigned.assigned_date,'YYYY-MM-DD') <= '2006-07-14' ORDER BY UPPER(target_date)
The error is
ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select listYou can't use the alias in the order by clause. And what about :
SCOTT@demo102> select ename,
2 case when sal >= 30000 then 'Very high'
3 when sal >= 20000 then 'High'
4 when sal >= 10000 then 'Medium'
5 else 'Low' end as SalStatus
6 from emp
7 order by SalStatus;
ENAME SALSTATUS
CLARK High
BLAKE High
JONES High
JAMES Low
SMITH Low
ALLEN Medium
WARD Medium
MILLER Medium
MARTIN Medium
TURNER Medium
ADAMS Medium
SCOTT Very high
FORD Very high
KING Very high
14 rows selected.
SCOTT@demo102> Nicolas.
Maybe you are looking for
-
How to install apex (and mapviewer) company wide ?
Hi, Until now I've developed some applications on a laptop. I want to bring them to my company - in this stage as a "pilot" with a limited number of employees having access. What do I need: a database, apex installed and - now is coming what I want t
-
Files uploaded to iCloud Drive also taking up space on local hard drive
Hello all! Quick question: Why are files uploaded to iCloud Drive also taking up space on my hard drive? I want to use my iCloud Drive for cloud based back up of certain files. I do not want these files to sync automatically, but to live in the clo
-
STOCK OF FINISHED PRODUCT BY PIR NOT CONSIDERING WHILE TAKING MRP RUN
DEAR SAPGURUS, I have finished product stock of 50 nos through planned independent requairement. now i am creating sales order for finished product but mrp run generate the planned order for finished product. I dont have planned order for fini
-
I need help. When I restored my hard drive and tried to open dreamweaver it gave me this error message 150:30. It's telling me that the licensing for this product has stopped working. Can you explain
-
Customer Master Data interface to external using Seeburger on MDMP
Hi Experts, Currently, customer master data is interfaced to external system via IDOC. The middleware used is Seeburger. If the system is changed to MDMP, would there be any impact to this interface? Is Seeburger communicates in Unicode? If