Use MAX with a Group By

Johnathan Simpson 586 Reputation points
2021-05-11T18:31:29.657+00:00

I want to return MAX() of the lines for an order. Even though In my query I do Max(ln) it still returns the line number.

How would this query need to be set-up so that MAX() returns MAX()

Create Table #Test
(
    ordernumber varchar(100)
    ,linenumber int
    ,item varchar(100)
)

Create Table #SaleData
(
    ordernumber varchar(100)
    ,salesperson varchar(250)
)

Insert Into #Test Values
('ABC-123', 1, 'shoe'), ('ABC-123', 2, 'sock'), ('ABC-123', 3, 'cap'), ('ABC-123', 4, 'mit')
,('RST-111', 1, 'shoe'), ('RST-111', 2, 'shirt'), ('EEA-123', 1, 'ball')

Insert Into #SaleData Values
('ABC-123', 'Mitchell'), ('RST-111', 'Jason'), ('EEA-123', 'Bob')

Select
sd.Ordernumber
,MAX(t.LineNumber) As Maxln
,t.item
,t.linenumber
FROM #SaleData sd
Join #Test t
ON t.ordernumber = sd.ordernumber
GROUP BY sd.ordernumber, t.linenumber, t.item

What i'd like to have returned for max is below
ABC-123 4
EEA-123 1
RST-111 2

but i also need to return the other data.

This is using ms sql server 2016

Developer technologies | Transact-SQL
{count} votes

2 answers

Sort by: Most helpful
  1. Tom Cooper 8,486 Reputation points
    2021-05-11T18:44:48.14+00:00

    If I understand what you want, then
    Select
    sd.Ordernumber
    ,MAX(t.LineNumber) Over(Partition By sd.Ordernumber) As Maxln
    ,t.item
    ,t.linenumber
    FROM #SaleData sd
    Join #Test t
    ON t.ordernumber = sd.ordernumber

    If that does not give you want you want, please show us what you want your query to return given your sample data.
    Tom

    2 people found this answer helpful.

  2. EchoLiu-MSFT 14,621 Reputation points
    2021-05-12T02:44:32.02+00:00

    Hi @Johnathan Simpson ,

    Please also check:

        ;WITH cte  
         as( Select sd.Ordernumber,MAX(t.LineNumber) As Maxln  
             FROM #SaleData sd  
             Join #Test t ON t.ordernumber = sd.ordernumber  
             GROUP BY sd.ordernumber)  
           
         Select * from cte c  
         Join #Test t  
         ON t.ordernumber = c.ordernumber  
    

    Output:
    95746-image.png

    If you have any question, please feel free to let me know.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.