Avatar of LeifHurst
 asked on

SQL Command (Sub select statement?)

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
       Select First(transaction) = 'NBS'
Microsoft SQL ServerDB Reporting ToolsMicrosoft SQL Server 2008

Avatar of undefined
Last Comment

8/22/2022 - Mon

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'
Francis Omoruto

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question

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
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck