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
Frank
So, 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
Similar Messages
-
Use DISTINCT with two fields to return one record
I am using OleDB with a SELECT DISTINCT query that is used in C# code to populate a DataGridViewComboBox. The queried table has two fields: ID and Description. The ID field values are unique. Descriptions may be duplicated. The DataSource of my DataGridViewComboBox
is ListBoxItems which is a ListBox that is populated from a table. The ValueMember is ID and the DisplayMember is Description. A sample table might look like this:
ID Description
1 Blue
2 Blue
3 Red
4 Blue
I want my query to return two records; one for the Red description and only one for the Blue description. I don't care which Blue description it returns, but I do need the corresponding ID for the selected Blue record and the ID value for the Red record.
Using SELECT DISTINCT ID, Description FROM... would give me four records instead of two. How can I return only two records in this scenario?
Rob E.Using window function:
create table #temp
ID int,
description varchar(20),
insert into #temp Values(1,'blue')
insert into #temp Values(2,'blue')
insert into #temp Values(3,'red')
insert into #temp Values(4,'blue')
;WITH CTE AS (select RN=ROW_NUMBER() OVER (PARTITION BY description ORDER BY newid() ),
ID,description from #temp)
SELECT ID, description from CTE
WHERE RN = 1;
ID description
4 blue
3 red
Kalman Toth Database & OLAP Architect
SQL Server 2014 Database Design
New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014 -
Service order creation using bapi with repair order number
Hi experts,
Pls suggest me a BAPI to create a service order for those repair orders where a PGR has been done(for return delivery type : LR).
The plant should be 0260 with storage location wh01 and item category ZRRE
Creation of a service order with repair order type SM03 is not allowed in iw31.
thanks and regards,
Vijayb.Hi prakash,
Thank u for the BAPI
But an error is being displayed saying that the REFURBISHMENT ORDERS CANNOT BE PROCESSED USING BAPI.
ERROR DURING PROCESSING OF BAPI METHODS.
This is while u pass the order type as either ZM03 or SM01or SM02 or SM03.
pls help me on that.
thanks and regards,
Vijayb. -
Using Subcontracting with Sales Order Stock
Hi SDN Network,
We use the made to order setup so run MRP with the Sales Order as the basis of the demand. After that, we avail the services of a subcontractor to assemble the finished goods although we supply the subassembly and raw matls.
The PR generated during the MRP run has an account assignment of either M or E depending on the Item Cat in the sales order. From that PR, we create a subcon PO (item cat L). Problem is the PO generated is not showing up on the ME2O transaction. Does this mean that POs whose GR goes directly to Sales Order stock are not allowed in the system? I am able to post
We would still want to retain the 'reservation' of the materials using the Sales Order stock. But does it follow that you cannot use Sales Order Stock with subcontracting?
Did I miss out anything in the config? Is there another way to do this?
Thanks in advance!Hi
Subcontracting issue to subcontractor (special stock O) and sales order stock (special stock E) both have special stock indicators and hence not possible.
The process can be done as explained in the link below:
http://help.sap.com/saphelp_erp2005vp/helpdata/en/4d/2b90b043ad11d189410000e829fbbd/frameset.htm
Best regards
Ramki -
i use this
select count(distinct a.id_client) cant,
sum(decode(b.sex,'W',mount)) mount
from credit a,client b
where a.id_client = b.id_client
CANT MOUNT
11383 97305111.8
but if i want to use decode in the count, like this
select count(decode(b.sex,'W',distinct a.id_client)) cant,
sum(decode(b.sex,'W',mount)) mount
from credit a,client b
where a.id_client = b.id_client;
select count(decode(b.sex,'W',distinct a.id_client)) cant,
ERROR at line 1:
ORA-00936: missing expression
and if i use this query without distinct clause it work fine
select count(decode(b.sex,'W', a.id_client)) cant,
sum(decode(b.sex,'W',mount)) mount
from credit a,client b
where a.id_client = b.id_client;
CANT MOUNT
21668 97305111.8
what can i do, i want to get the quantity of clients by sex in diferents columns but i don't want to use a group by clause like this
select b.sex,count(a.id_client) cant
from credit a,client b
where a.id_client = b.id_client
group by b.sexTry this.
SELECT COUNT(DISTINCT DECODE(b.sex,'W',a.id_client,null)) cant,
SUM(DECODE(b.sex,'W',mount)) mount
FROM credit a,client b
WHERE a.id_client = b.id_client; -
Need help with select distinct with group by
RDBMS 10gr2
I am trying achieve having a select distinct with a order by and after looking on the internet and trying different examples, I have been unsucessful.
Here is the code working (not sorting - I wish to sort by pps.last_name however I can't seem to get it to work).
select distinct pps.last_name || ', ' ||pps.first_name || ' ' ||pps.middle_initial || '.' d,
emple_no r
from cobr.vw_pps_payroll pps,
projman pm
where term_date is null
and department = '0004400000'
and pm.eid != pps.emple_noSQL> SELECT ename || '-' || empno, sal
2 FROM emp_test
3 ORDER BY ename;
ENAME||'-'||EMPNO SAL
BLAKE-7698 20000
CLARK-7782 20000
DAVID-7699 20000
FORD-7902 6000
JONES-7566 5950
KING-7839 10000
SCOTT-7788 6000
7 ligne(s) sélectionnée(s).
SQL> -
How to use distinct while using a select that builds xml?
Hi.
Example:
SELECT
XMLELEMENT("Column1" value1
,"Column2" value2
,"Column3" value3
FROM a_table A
Where id_val = x
Imagine that this repeats a same result 4 times. If it was a simple query distinct would work...how can i use distinct with this?
Thanks.
Cheers!Hi,
what about group by
SQL> WITH A AS(SELECT 1 val1,2 val2,3 val3 FROM dual UNION ALL
2 SELECT 1 ,2 ,3 FROM dual UNION ALL
3 SELECT 1 ,2 ,3 FROM dual)
4 SELECT XMLElement("cols"
5 ,XMLElement("col1",val1)
6 ,XMLElement("col2",val2)
7 ,XMLElement("col3",val3))
8 FROM A
9 GROUP BY val1,val2,val3;
XMLELEMENT("COLS",XMLELEMENT("COL1",VAL1),XMLELEMENT("COL2",VAL2),XMLELEMENT("CO
<cols><col1>1</col1><col2>2</col2><col3>3</col3></cols> -
COUNT(DISTINCT) WITH ORDER BY in an analytic function
-- I create a table with three fields: Name, Amount, and a Trans_Date.
CREATE TABLE TEST
NAME VARCHAR2(19) NULL,
AMOUNT VARCHAR2(8) NULL,
TRANS_DATE DATE NULL
-- I insert a few rows into my table:
INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Anna', '110', TO_DATE('06/01/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Anna', '20', TO_DATE('06/01/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Anna', '110', TO_DATE('06/02/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Anna', '21', TO_DATE('06/03/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Anna', '68', TO_DATE('06/04/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Anna', '110', TO_DATE('06/05/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Anna', '20', TO_DATE('06/06/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Bill', '43', TO_DATE('06/01/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Bill', '77', TO_DATE('06/02/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Bill', '221', TO_DATE('06/03/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Bill', '43', TO_DATE('06/04/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
INSERT INTO TEST ( TEST.NAME, TEST.AMOUNT, TEST.TRANS_DATE ) VALUES ( 'Bill', '73', TO_DATE('06/05/2005 08:00:00 PM', 'MM/DD/YYYY HH12:MI:SS PM') );
commit;
/* I want to retrieve all the distinct count of amount for every row in an analytic function with COUNT(DISTINCT AMOUNT) sorted by name and ordered by trans_date where I get only calculate for the last four trans_date for each row (i.e., for the row "Anna 110 6/5/2005 8:00:00.000 PM," I only want to look at the previous dates from 6/2/2005 to 6/5/2005 and get the distinct count of how many amounts there are different for Anna). Note, I cannot use the DISTINCT keyword in this query because it doesn't work with the ORDER BY */
select NAME, AMOUNT, TRANS_DATE, COUNT(/*DISTINCT*/ AMOUNT) over ( partition by NAME
order by TRANS_DATE range between numtodsinterval(3,'day') preceding and current row ) as COUNT_AMOUNT
from TEST t;
This is the results I get if I just count all the AMOUNT without using distinct:
NAME AMOUNT TRANS_DATE COUNT_AMOUNT
Anna 110 6/1/2005 8:00:00.000 PM 2
Anna 20 6/1/2005 8:00:00.000 PM 2
Anna 110 6/2/2005 8:00:00.000 PM 3
Anna 21 6/3/2005 8:00:00.000 PM 4
Anna 68 6/4/2005 8:00:00.000 PM 5
Anna 110 6/5/2005 8:00:00.000 PM 4
Anna 20 6/6/2005 8:00:00.000 PM 4
Bill 43 6/1/2005 8:00:00.000 PM 1
Bill 77 6/2/2005 8:00:00.000 PM 2
Bill 221 6/3/2005 8:00:00.000 PM 3
Bill 43 6/4/2005 8:00:00.000 PM 4
Bill 73 6/5/2005 8:00:00.000 PM 4
The COUNT_DISTINCT_AMOUNT is the desired output:
NAME AMOUNT TRANS_DATE COUNT_DISTINCT_AMOUNT
Anna 110 6/1/2005 8:00:00.000 PM 1
Anna 20 6/1/2005 8:00:00.000 PM 2
Anna 110 6/2/2005 8:00:00.000 PM 2
Anna 21 6/3/2005 8:00:00.000 PM 3
Anna 68 6/4/2005 8:00:00.000 PM 4
Anna 110 6/5/2005 8:00:00.000 PM 3
Anna 20 6/6/2005 8:00:00.000 PM 4
Bill 43 6/1/2005 8:00:00.000 PM 1
Bill 77 6/2/2005 8:00:00.000 PM 2
Bill 221 6/3/2005 8:00:00.000 PM 3
Bill 43 6/4/2005 8:00:00.000 PM 3
Bill 73 6/5/2005 8:00:00.000 PM 4
Thanks in advance.you can try to write your own udag.
here is a fake example, just to show how it "could" work. I am here using only 1,2,4,8,16,32 as potential values.
create or replace type CountDistinctType as object
bitor_number number,
static function ODCIAggregateInitialize(sctx IN OUT CountDistinctType)
return number,
member function ODCIAggregateIterate(self IN OUT CountDistinctType,
value IN number) return number,
member function ODCIAggregateTerminate(self IN CountDistinctType,
returnValue OUT number, flags IN number) return number,
member function ODCIAggregateMerge(self IN OUT CountDistinctType,
ctx2 IN CountDistinctType) return number
create or replace type body CountDistinctType is
static function ODCIAggregateInitialize(sctx IN OUT CountDistinctType)
return number is
begin
sctx := CountDistinctType('');
return ODCIConst.Success;
end;
member function ODCIAggregateIterate(self IN OUT CountDistinctType, value IN number)
return number is
begin
if (self.bitor_number is null) then
self.bitor_number := value;
else
self.bitor_number := self.bitor_number+value-bitand(self.bitor_number,value);
end if;
return ODCIConst.Success;
end;
member function ODCIAggregateTerminate(self IN CountDistinctType, returnValue OUT
number, flags IN number) return number is
begin
returnValue := 0;
for i in 0..log(2,self.bitor_number) loop
if (bitand(power(2,i),self.bitor_number)!=0) then
returnValue := returnValue+1;
end if;
end loop;
return ODCIConst.Success;
end;
member function ODCIAggregateMerge(self IN OUT CountDistinctType, ctx2 IN
CountDistinctType) return number is
begin
return ODCIConst.Success;
end;
end;
CREATE or REPLACE FUNCTION CountDistinct (n number) RETURN number
PARALLEL_ENABLE AGGREGATE USING CountDistinctType;
drop table t;
create table t as select rownum r, power(2,trunc(dbms_random.value(0,6))) p from all_objects;
SQL> select r,p,countdistinct(p) over (order by r) d from t where rownum<10 order by r;
R P D
1 4 1
2 1 2
3 8 3
4 32 4
5 1 4
6 16 5
7 16 5
8 4 5
9 4 5buy some good book if you want to start at writting your own "distinct" algorythm.
Message was edited by:
Laurent Schneider
a simpler but memory killer algorithm would use a plsql table in an udag and do the count(distinct) over that table to return the value -
I ordered my Macbook Air with Aperture two years ago. I now have an iMac - can I use that with Aperture in any way? I appreciate that it is a different computer but I am now the end user of both devices and I was just wondering if it was possible.
Thanks,
SeanThe answer would be in your software license agreement for Aperture. However if you cannot locate it you can ask in the Aperture forum, the link for that is:
https://discussions.apple.com/community/professional_applications/aperture
However I believe you can have Aperture installed on two machines however only one may be using it at a time.
On the new iMac launch the Mac App Store - Purchased - look for Aperture and download to your new machine. -
Problem in Sales order create using BAPI with reference to quotation
Hi,
I am creating a sales order from Quotation using BAPI /AFS/BAPI_SALESORD_CREATEFDATA.
The Sale order is getting created and the document flow is updated. When i check the status of quotation it is "OPEN".
Ideally when a sale order is created in VA01 with reference to a quotation and if all items are added in the order from quotation, then the status of the quotation must be "Complete".
When i use the BAPI, the status of the quotation is sill "Open". Has anyone faced this issue?
Even if anyone has faced this issue with BAPI_SALESORDER_CREATEFROMDAT2, please let me know...
RegardsHi RV,
I am using BAPI to create order reference to contracts. I am facing same issue. Its not updating document flow (vbfa-plmin field). After creating orders I am forcing to update plmin field in vbfa. This worked fine. But now status in reference document not updating properly. I saw your thread. It looks like similar issue. I saw your comments "Customization was not maintained properly for the Order types ". Please can you explain little bit more about your solution. It will helps us lot.
Thanks,
srini -
SSRS reporting with sharepoint list using Distinct and Multivalue parameters
i want create ssrs report with sharepoint list using ms-vs(2008). i want create Distinct multivalue parameters by using CAML query. There is any way we put CAML query where we use Distinct keyword and IN clause in CAML query... i hope all experts will
understand my poor English... sorry for poor English.. plz help meHi AsifMehmood,
Per my understanding you have create an SSRS report with SharePoint list, now you don’t know to create the distinct parameters by using CAML query, right?
For the CAML language doesn’t have any reserved word (or tag) to set this particular filter to remove duplicate results, but we can use the custom code to do this function. I have tested on my local environment and we can do that by create one hidden parameter(Param1)
to get all the values from the fields which will add the filter and then create another parameter(Param2) to get the distinct values based on the Param1, we use the custom code to do the deduplication.
Step by Steps information in below thread for your reference to create the parameters and the custom code:
"How to get distinct values of sharepoint column using SSRS"
Other similar thread for your reference:
https://audministrator.wordpress.com/2014/02/17/sharepoint-list-add-distinct-parameter-value/
If your problem still exists, please feel free to ask and also try to provide us more details information.
Regards
Vicky Liu -
How can I use WM_CONCAT with DISTINCT in a stored provedure?
Hi,
I join three tables. For example one is for employees, other is for employee address, and the last one is for the cities of employees that work. I want to take the employee id, address city, and working cities. It is like the table below, but I want one line for each employee, so I used WM_CONCAT. Because there is duplicate data, I used DISTINCT in WM_CONCAT. It works fine normally, but if I want to use it in a stored procedure it gives an error :ORA-30482: DISTINCT option not allowed for this function. Is there anyone who could solve this problem? Thank in advance.
EXP_ID CITY_ADDRESS CITY_WORK
1 IZMIR IZMIR
2 IZMIR DENIZLI
2 IZMIR IZMIR
2 IZMIR IZMIR
Edited by: 878596 on 10.Ağu.2011 22:48WM_CONCAT is an undocumented function. It is used only for Oracle Internal Purpose. You are not supposed to use it. Never use any Undocumented feature of Oracle. That could get you into trouble.
Said that if you can tell us exactly what problem are you trying to solve with WM_CONCATE we could give you a better solution without using WM_CONCATE.
Please read the Link How to ask a question in this forum? To post the question in a proper way.
SQL and PL/SQL FAQ -
How to create updateable resultset using sql with "order by"
Dear all,
I'm using the Derby database to hold a table of stock prices. After the table is populated, I want to do some calculations and store the result in a column.
I get the resultset using the following code
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery(select history_id, value, days from history where ticker = '" + ticker + "' order by value_date"); {code} When I then try to update the "days" field, I get an SQLException telling me that the resultset is not updatable. However, if I remove the "order by" clause, I am able to update the data, but then my algorithm does not work as I need to traverse the data in a specific order. The quesion is: how do I create an updatable resultset using a sql-statement with an order by clause? Kind regards Karl Martin Lundjschell wrote:
Seems rather obvious to me that the exception specifically tells you that you can't do that.OP: I would guess it's because ORDER BY forces the database to read all the result rows into a temporary area, sort them, and then return them from this temporary area, as opposed to streaming the results. The extra step probably makes updateable result sets more difficult (or maybe not possible), so they opted not to do it. -
Query to find no of peoples with the same age(using distinct)
query to find no of peoples with the same age(using distinct)
Edited by: swordfish3 on Mar 7, 2009 9:24 PMit would be helpful if you posted some proper sample data with proper expected results.
The easier you make it for us to help you, the more likely you will get helped. -
HT204032 Why can you not use powernap with a custom order iMac with solid state?
Why can you not use powernap with a custom order iMac with solid state?
Find it quite ridiculous that a 3 year old mba supports it and not a new iMacAgreed. Why wouldn't you want your Photostream updated while your iMac is sleeping? I am bummed about this.
Maybe you are looking for
-
Creating a Process Chain for a Broadcasting Precalc
Friends - Can a process chain be created for a Broadcasting Precalc? If yes, does anyone have any steps on how to do this? Thanks!
-
Nomad Jukebox ZEN Xtra stuck in safe m
Stuck in safe mode, no matter what option I choose it's stuck there in rescue mode. And now my laptop won't detect it as a device. I've downloaded and installed new device drivers and nothing, still unable to install the device. Basically, I need it
-
Sender Email Adapter in PI 7.11 by using the IMAP
Hi Experts I am trying to configure a sender email adapter by using the IMAP Protocal , Can anyone send the blog or paramertes to configure for IMAP Protocal I did find for POP3 Thanks PR
-
How i can open the form in Internet Explorer
Dears. I am using Developer 6i and Oracle8. I want to learn how i can execute my form in IE. Please teach me about that how i can be able to execute my form in IE. waiting for reply Zaheer
-
Firefox wants to save a pdf I select online. How can I just read it?
When I select a pdf online, Firefox is set to save the file somewhere. How can I change this so that I can just read the pdf, then decide to save it later?