Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Ordering problem 1

Status
Not open for further replies.

rawkin

Programmer
Sep 23, 2003
11
AU
Hi,

I have two tables, one containing account details and the second containing the account history. I'm trying to pull the date the account was last updated along with the account details in a single query;

SELECT
a.id, a.contact_name, a.username, a.status, b.timestamp
FROM
accounts a, history b
WHERE
(a.id = b.account_id)
GROUP BY username;

The only problem with this query is that it returns the timestamp of the first history record, rather than the last history record for that user. Is there a way to incorporate some sort of 'ORDER BY b.timestamp' prior to the 'GROUP BY' ?

thanks,

Pete
 
This should work:
[tt]
SELECT
a.id,a.contact_name,a.username,a.status,
MAX(b.timestamp)
FROM
accounts a JOIN history b ON a.id=b.account_id
GROUP BY a.username
[/tt]
 
Sorry, that should be:
[tt]
SELECT
a.id,a.contact_name,a.username,a.status,
MAX(b.timestamp)
FROM
accounts a JOIN history b ON a.id=b.account_id
GROUP BY a.id
[/tt]
 
That's done the trick :) thanks very much for your help.

Pete
 
A small add-on to this problem ;)

The query provides the entire list of customers with their last contact time. Now I'm trying to order the entire list by the contact time so the most recently contacted are displayed at the top.

I tried;

SELECT
a.id,a.contact_name,a.username,a.status,
MAX(b.timestamp)
FROM
accounts a JOIN history b ON a.id=b.account_id
GROUP BY a.id ORDER BY b.timestamp DESC

This returns a mostly ordered list, but some entries appear completely out of place .. I suspect this is a result of the use of GROUP BY. Is there another approach to ordering the results by timestamp?

thanks,

Pete
 
How about:
[tt]
SELECT
a.id,a.contact_name,a.username,a.status,
MAX(b.timestamp) t
FROM
accounts a JOIN history b ON a.id=b.account_id
GROUP BY a.id
ORDER BY t DESC
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top