all groups > sql server mseq > october 2003 >
You're in the

sql server mseq

group:

Need Help with Query


Need Help with Query Bill
10/21/2003 4:08:19 PM
sql server mseq: I have a problem I am trying to currently solve. I want
to return the row with the Max Cycle Number for each
order. In the below example there are 3 rows for one
order and 2 rows for another order. I want to return 2
rows: OrdId = 19852, Cycle = 52 and OrdId 20155, Cycle =
51. Can anyone help me with this?

Bill

OrdID Cycle Status MailDate
19852 52 Mailed 10/10/2003
19852 50 Mailed 10/07/2003
19852 51 Mailed 10/09/2003
20155 51 Mailed 10/09/2003
20155 50 Mailed 10/08/2003

The below SQL is not getting the job done.

SELECT OpenOrders.OrdID, Max(OpenOrders.Cycle) AS
MaxOfCycle, OpenOrders.Status, OpenOrders.MailDate
FROM OpenOrders
WHERE ((OpenOrders.Status)="Mailed") AND
((OpenOrders.MailDate) Is Not Null)
GROUP BY OpenOrders.OrdID, OpenOrders.Status,
OpenOrders.MailDate
HAVING ((Max(OpenOrders.Cycle) <>"False"))
Re: Need Help with Query I_AM_DON_AND_YOU?
10/21/2003 4:45:13 PM
(Not tested...but should run)

SELECT A.OrdID, A.MailDate.A.Cycle
FROM OpenOrders A
WHERE
A.Status = "Mailed" AND
A.MailDate IS NOT NULL AND
A.OrdID =
(SELECT B.OrdID FROM OpenOrders B
B.OrdID = A.OrdID
AND B.Cycle = (SELECT TOP 1 Max(C.Cycle) from OpenOrders where C.OrdID =
B.OrdID)))


[quoted text, click to view]

Need Help with Query (neither sln works) Bill
10/22/2003 8:41:04 AM
Thanks for the help but neither solution worked when I
ran them.

I still got a row for each cycle number.


[quoted text, click to view]
Re: Need Help with Query Vishal Parkar
10/22/2003 1:17:40 PM
Bill,

My assumption is you want #to retrieve each row #table for a particular ordid
where cycle's column value is maximum out of other rows. If #this is #true you can
try query shown in following example.

drop table #t
create table #t (OrdID int, Cycle int,Status varchar(10),MailDate datetime)
insert into #t
select 19852 ,52 ,'Mailed', '10/10/2003' union all
select 19852 ,50 ,'Mailed', '10/07/2003' union all
select 19852 ,51 ,'Mailed', '10/09/2003' union all
select 20155 ,51 ,'Mailed', '10/09/2003' union all
select 20155 ,50 ,'Mailed', '10/08/2003'

--Required query.

select * from #t as a
where exists
(select ordid, max(cycle) cycle from
#t where #t.ordid = a.ordid
group by ordid
having max(#t.cycle) = a.cycle )

You can add additional where clauses to the above query to do more filteration.

--
-Vishal

Re: Need Help with Query (neither sln works) Vishal Parkar
10/22/2003 11:41:49 PM
Bill,

That should not be possible with the solution i've posted. It returns the 1 row for each
ordid, as per the requirement that you've posted earlier. If this doesn't satisfy your
requirement post DDL/more "relevant" sample records/ and the exact expected resultset.

--
-Vishal



AddThis Social Bookmark Button