SQL Command (Sub select statement?)

LeifHurst
LeifHurst used Ask the Experts™
on
I'm still a novice with SQL queries but I'm needing assistance with a query that is giving me some trouble for a report.

Here's some sample data

Customer | Transaction | TranDate | InvoiceAmt
1 NBS 01/01/2011 1000
1 UPD 02/01/2011 500
1 UPD 03/01/2011 100
1 UPD 04/01/2011 200
1 UPD 05/01/2011 100
2 RWL 01/01/2011 800
2 UPD 02/01/2011 350
2 CNL 03/01/2011 400
3 RWL 01/01/2011 500
3 NBS 02/01/2011 500

What I'm needing to do is to query all rows where the customers with the first appearance or oldest Transactions = NBS. I don't need the NBS row by itself, I need the resultant set where the first row is equal to NBS and then all other rows for that customer as well.

In the example below the query would return all rows for customer #1 only because the oldest entry is NBS.

Can I do this with a "sub select" statement in my query (not sure if this is the right term)...

(this is rough but just to convey the idea of what I'm trying to get)
Select Customer, Transaction,  TranDate, InvoiceAmt
From Customer_Table
Where
       Select First(transaction) = 'NBS'
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Select Customer, Transaction,  TranDate, InvoiceAmt
From Customer_Table C
join (Select Customer, min(TranDate) as MinTranDate from Customer_Table group by Customer) S
  on S.Customer = C.Customer
 and S.MinTranDate = C.TranDate
and C.Transaction = 'NBS'
Infrastructure and Database Design Consultant
Commented:
A slight adjustment to the above:

Select C.Customer, C.[Transaction],  C.TranDate, C.InvoiceAmt
From simpletrade C
where c.Customer in (
Select x.Customer
From simpletrade x
join (Select Customer, min(TranDate) as MinTranDate from simpletrade group by Customer) S
  on S.Customer = x.Customer
 and S.MinTranDate = x.TranDate
and x.[Transaction] = 'NBS')

Open in new window

Top Expert 2011

Commented:
Select Customer, Transaction,  TranDate, InvoiceAmt
From Customer_Table as C
Inner join (select customer
                   from (select customer ,transaction,
                             row_number() over (partition by customer
                                 order by trandate) as rn
                             from customer_table
                            ) as z
                   where rn=1 and transaction='NBS'
                ) as x
on c.customer=x.customer
order by customer,trandate

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial