3

I have some trouble with grouping the data by the order number and aggregating the "support columns" while selecting always the "highest" value.

╔═════════════╦══════════════╦════════════════╗
║ OrderNumber ║ PhoneSupport ║ ServiceSupport ║
╠═════════════╬══════════════╬════════════════╣
║ 0000000001  ║ 0020         ║                ║
║ 0000000001  ║ 0010         ║ 0030           ║
║ 0000000001  ║ 0010         ║ 0020           ║
║ 0000000002  ║              ║ 0030           ║
║ 0000000002  ║ 0030         ║                ║
║ 0000000003  ║ 0020         ║                ║
║ 0000000003  ║ 0030         ║                ║
╚═════════════╩══════════════╩════════════════╝

In this example the output should be like this.

╔═════════════╦══════════════╦════════════════╗
║ OrderNumber ║ PhoneSupport ║ ServiceSupport ║
╠═════════════╬══════════════╬════════════════╣
║ 0000000001  ║ 0020         ║ 0030           ║
║ 0000000002  ║ 0030         ║ 0030           ║
║ 0000000003  ║ 0030         ║                ║
╚═════════════╩══════════════╩════════════════╝

So far I have often read in various forums something about cursors but I don't like to use it.

My idea was to use the over clause but I am not sure if it is a solution for that case.

2 Answers 2

4

Use GROUP BY, do MAX on the columns you want the "highest" value for.

select OrderNumber, max(PhoneSupport), max(ServiceSupport)
from tablename
group by OrderNumber
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for opening my eyes. I simplified the problem in my question, with your short but correct answer I recognized that the problem is in the cte before...
1

You can use Group By and Max and then wrap the query in parent to do Order By on aggregate columns. Example shown below.

select * 
from (
    select OrderNumber, max(PhoneSupport) as PhoneSupport, max(ServiceSupport)  as ServiceSupport
    from tablename
    group by OrderNumber) aa
Order By aa.PhoneSupport

2 Comments

That derived table is unneeded.
Can't you just put the ORDER BY at the end, without using a derived table? Or is that some kind of MS SQL Server limitation?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.