Extract the TOP 1 of each item within the Table in Ms Sql

We have a sales table with where an invoice can have 2 type of transactions: ‘Invoice’ and ‘PreQtrInvoice’.  The table consists of a document number representing the invoice number for the sales and a type for the Items sold.

We are trying to display only the first ‘PreQtrInvoice’of an Item within each document number (like TOP 1 sorting by ‘PreQtrInvoice’).  If the item has no ‘PreQtrInvoice’ within its document number, then include in the list the first Invoice type

The data is:
Data:
DocNumber Product DocType        StockQy
Doc1      Prod-A  PreQtrInvoice  1
Doc1      Prod-A  Invoice        3
Doc1      Prod-B  PreQtrInvoice  5
Doc1      Prod-B  PreQtrInvoice  5
Doc1      Prod-B  Invoice        1
Doc1      Prod-C  Invoice        1
Doc2      Prod-D  Invoice        2
Doc2      Prod-E  Invoice        2
Doc3      Prod-F  PreQtrInvoice  1
Doc3      Prod-G  Invoice        7
Doc3      Prod-F  Invoice        3

Open in new window


The expected result is:
DocNumber Product DocType        StockQy
Doc1      Prod-A  PreQtrInvoice  1
Doc1      Prod-B  PreQtrInvoice  5
Doc1      Prod-C  Invoice        1
Doc2      Prod-D  Invoice        2
Doc2      Prod-E  Invoice        2
Doc3      Prod-F  PreQtrInvoice  1
Doc3      Prod-G  Invoice        7

Open in new window


Upto now we see 2 separate script.  One to extract the TOP 1 of ‘PreQtrInvoice’ and another to display items with ‘‘PreQtrInvoice’ and display the first one of their document number.
rayluvsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

rayluvsAuthor Commented:
Here is a sample of the data:
-- Create Table
    DECLARE @Sales TABLE(
                     DocNumber VARCHAR(20),
                     Product VARCHAR(20),
                     DocType VARCHAR(20),
                     StockQy INT)
-- Insert data
   INSERT INTO @Sales SELECT 'Doc1','Prod-A','PreQtrInvoice', 1
   INSERT INTO @Sales SELECT 'Doc1','Prod-A','Invoice', 3
   INSERT INTO @Sales SELECT 'Doc1','Prod-B','PreQtrInvoice', 5
   INSERT INTO @Sales SELECT 'Doc1','Prod-B','PreQtrInvoice', 5
   INSERT INTO @Sales SELECT 'Doc1','Prod-B','Invoice', 1
   INSERT INTO @Sales SELECT 'Doc1','Prod-C','Invoice', 1
   INSERT INTO @Sales SELECT 'Doc2','Prod-D','Invoice', 2
   INSERT INTO @Sales SELECT 'Doc2','Prod-E','Invoice', 2
   INSERT INTO @Sales SELECT 'Doc3','Prod-F','PreQtrInvoice', 1
   INSERT INTO @Sales SELECT 'Doc3','Prod-G','Invoice', 7
   INSERT INTO @Sales SELECT 'Doc3','Prod-F','Invoice', 3

-- Display Table
   SELECT * from @Sales
   ORDER BY DocNumber, Product asc

Open in new window




Below is the results of the above marking the lines the script we are working trying to accomplish:
DocNumber            Product              DocType              StockQy
-------------------- -------------------- -------------------- -----------
Doc1                 Prod-A               PreQtrInvoice        1  < ---- DISPLAY THIS LINE
Doc1                 Prod-A               Invoice              3
Doc1                 Prod-B               PreQtrInvoice        5  < ---- DISPLAY THIS LINE
Doc1                 Prod-B               PreQtrInvoice        5
Doc1                 Prod-B               Invoice              1
Doc1                 Prod-C               Invoice              1  < ---- DISPLAY THIS LINE
Doc2                 Prod-D               Invoice              2  < ---- DISPLAY THIS LINE
Doc2                 Prod-E               Invoice              2  < ---- DISPLAY THIS LINE
Doc3                 Prod-F               PreQtrInvoice        1  < ---- DISPLAY THIS LINE
Doc3                 Prod-F               Invoice              3
Doc3                 Prod-G               Invoice              7  < ---- DISPLAY THIS LINE

Open in new window

0
Christopher GordonSenior Developer AnalystCommented:
See attach sample using row counter to sort invoices.  Note: SQL 2008 syntax used for populating table.
Invoice-Sample-SQL.sql
0
Brian CroweDatabase AdministratorCommented:
;WITH cteInvoice (DocNumber, Product, DocType, StockQy, RowNumber)
AS
(
      SELECT DocNumber, Product, DocType, StockQy,
            ROW_NUMBER() OVER (PARTITION BY DocNumber, Product ORDER BY DocType DESC) AS RowNumber
      FROM @Sales
)
SELECT * FROM cteInvoice
WHERE RowNumber  = 1

If there is some way to order the PreQtrInvoice types then I would include that in the ROW_NUMBER calculation otherwise there is no way to guarantee which one you will get for a given DocNumber/Product
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
10 Tips to Protect Your Business from Ransomware

Did you know that ransomware is the most widespread, destructive malware in the world today? It accounts for 39% of all security breaches, with ransomware gangsters projected to make $11.5B in profits from online extortion by 2019.

rayluvsAuthor Commented:
gohord, we're getting a syntax error at the first "('Doc1',".

 BriCrowe, it worked excellently.  How can we display only the result?  When adding your portion, it does a full table display, then the result.

Here is the last portion of the script after adding your lines:
-- Display Table
   SELECT * from @Sales
   ;WITH cteInvoice (DocNumber, Product, DocType, StockQy, RowNumber)
AS
(
      SELECT DocNumber, Product, DocType, StockQy,
            ROW_NUMBER() OVER (PARTITION BY Product ORDER BY DocType DESC) AS RowNumber
      FROM @Sales
)
SELECT * FROM cteInvoice
WHERE RowNumber  = 1
ORDER BY DocNumber, Product asc

Open in new window

0
PortletPaulfreelancerCommented:
>>How can we display only the result?

by removing this:

  SELECT * from @Sales

----
no points please
0
rayluvsAuthor Commented:
Yes!  Thanx worked!


Can you explain a bit on the use of

ROW_NUMBER() OVER (PARTITION BY Product ORDER BY DocType DESC) AS RowNumber

and

WHERE RowNumber  = 1

in order to get the result?
0
PortletPaulfreelancerCommented:
ROW_NUMBER()
Ths "analytic function" supplies integers staring at 1 as determined by the over() clause that follows it


OVER()

PARTITION BY >> this is similar to a "group by"; so for each "partition" the row_number will restart at 1, here you are partitioning by product

ORDER BY  >> same as any order by, but here we use it to start the numbering at doctype DESC(ending)
so if a partition has 'PreQtrInvoice' this will get a 1
if it does not then have 'PreQtrInvoice'  then 'Invoice' will get a 1
every other record for the same product gets a row_number of 2 or higher

then you use
WHERE RowNumber  = 1

so that only one record per product is chosen
(as determined by the partition by and order by i the over() clause)
0
Brian CroweDatabase AdministratorCommented:
PortletPaul thanks for picking up my slack :-)
0
PortletPaulfreelancerCommented:
no problem BriCrowe happy to lend a hand.
0
rayluvsAuthor Commented:
Thanx Lots!  You guys are Great!
0
rayluvsAuthor Commented:
Thanx!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Query Syntax

From novice to tech pro — start learning today.