0

Following is my table structure with data

id  orderNO lineItemNO  orderStatus
1   100     1           Processing
2   100     2           Processing
3   100     3           Pending
4   101     1           Pending
5   101     2           Pending

i have orderNo and line item no column which represents the no of products in the order. Now i want only that orders and lineItemNo whose orderStatus is same.

for example

Order No with 100 has 3 line items (1,2,3) but line item no (1 and 2) has orderStatus as Processing ans line item no (3) has orderStatus has Pending so i dont want this order.

Now order No with 101 has 2 line items (1,2) and all line items from the same order has the same order status so i need order 101.

So looking for the SQL query for the same.

I need output as

id  orderNO lineItemNO  orderStatus
4   101     1           Pending
5   101     2           Pending

Please Help me

1 Answer 1

2

Some creative thinking about sets should demonstrate that we can determine this by finding the MIN() and MAX() values within each group and comparing them - if they're equal then there cannot be any other value within the same group:

declare @t table (id int,orderNO int,lineItemNO int,orderStatus varchar(317))
insert into @t(id,orderNO,lineItemNO,orderStatus) values
(1,100,1,'Processing'),
(2,100,2,'Processing'),
(3,100,3,'Pending'),
(4,101,1,'Pending'),
(5,101,2,'Pending')

;With MinMax as (
    select *,
        MIN(orderStatus) OVER (PARTITION BY orderNo) as minStat,
        MAX(orderStatus) OVER (PARTITION BY orderNo) as maxStat
    from
        @t
)
select * from MinMax where minStat = maxStat

Produces the result:

id          orderNO     lineItemNO  orderStatus       minStat           maxStat
----------- ----------- ----------- ----------------- ----------------- -----------------
4           101         1           Pending           Pending           Pending
5           101         2           Pending           Pending           Pending
1
  • thanks for the answer it has been worked. thanks a lot Aug 11, 2016 at 7:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.