Jump to content

Recommended Posts

I have a table with two columns:

 

ID    Date

1      2010-9-28

1      2010-9-27

2      2010-8-28

2      2010-8-27

 

 

I want to group the ids and return the earliest (and later, the latest) dates corresponding to that id. for example:

 

1      2010-9-28

2      2010-8-28

 

 

The problem is that the grouping is done before the ordering. I would use HAVING, but I don't have any solid value to create a condition. All the solutions I come up with involve a ridiculous amount of sub-queries. Any ideas?

 

Thanks for any help.

Link to comment
https://forums.phpfreaks.com/topic/214755-order-before-grouping/
Share on other sites

Thanks for the reply. I guess I didn't mean to say that I wanted to return the dates. I actually need to return the ID column. I tried doing a "WHERE MAX(date) = date" but that threw an error. I also tried with a HAVING clause.

 

This was the best I could come up with:

SELECT
			   (SELECT ID FROM dates WHERE ID = d.ID ORDER BY Date LIMIT 1) sid
			FROM
			   ids d
			GROUP BY
			   d.ID

 

Basically goes through all of the possible ids and gets the max for each one. I can't figure out how to make it work if I want it to only return the id if there are more than one entry with the same id.

 

Thanks for the help.

Hi

 

Think the code given earlier is almost what you want

 

SELECT id, MIN( date ), MAX( date )
FROM table 
GROUP BY id

 

If you only want ones where there is more than one row for the id

 

SELECT id, MIN( date ), MAX( date ), COUNT(*) AS DateCount
FROM table 
GROUP BY id
HAVING DateCount > 1

 

However I am not certain that is what you want

 

All the best

 

Keith

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.