Solved

Sql max column

Posted on 2009-05-14
5
383 Views
Last Modified: 2012-05-07
Hi

I am selecting records mulitple tables as follows

select distinct o.order_id, o.order_date, u.name, a.addressid
from orders o
inner join users u on o.user_id=u.user_id
inner join addresses a on u.user_id=a.user_id
where o.order_status='c'

I also want to add a column to the above which contains the max order_id from the above selected records.  

How can I acheive this?

Wing
0
Comment
Question by:WingYip
  • 3
  • 2
5 Comments
 
LVL 92

Accepted Solution

by:
Patrick Matthews earned 50 total points
ID: 24384489
select MAX(o.order_id) AS order_id, o.order_date, u.name, a.addressid
from orders o
inner join users u on o.user_id=u.user_id
inner join addresses a on u.user_id=a.user_id
where o.order_status='c'
GROUP BY o.order_date, u.name, a.addressid
0
 
LVL 1

Author Comment

by:WingYip
ID: 24384506
I am an idiot!
0
 
LVL 1

Author Closing Comment

by:WingYip
ID: 31581434
thanks
0
 
LVL 92

Expert Comment

by:Patrick Matthews
ID: 24384524
WingYip said:
>>I am an idiot!

No, you just need more coffee :)
0
 
LVL 1

Author Comment

by:WingYip
ID: 24384974
actually that doesnt work as it returns the highest order number within the grouping.

If there are a total of 300 records selected using the query above then I want to return the highest order_id out of those 300 records so that each row will show the same value for the MaxOrderId column (as below)

order_id    MaxOrderId
1                 4
2                 4
3                 4
4                 4
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Join & Write a Comment

How to leverage one TLS certificate to encrypt Microsoft SQL traffic and Remote Desktop Services, versus creating multiple tickets for the same server.
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now