1

I have a table with rows like below

id, name , phName , startDate, endDate

1   A    , Name      1-1-2011  5-1-2011

2   B    , Name      5-1-2011  10-10-2011

3   C    , Name      2-1-2011  11-10-2011

4   X    , XXName    2-1-2011  11-10-2011

Now I need to find the max(startDate) along with all other columns for a given phName.

Essentially, I want the resultset to look like below for phName of "Name"

max(startDate)
5-1-2011,         1   A    , Name      1-1-2011  5-1-2011

5-1-2011,         2   B    , Name      5-1-2011  10-10-2011

5-1-2011,         3   C    , Name      2-1-2011  11-10-2011

I don't want to use temp table to get the result set.

2
  • What DBMS are you using? Commented Jun 9, 2011 at 7:10
  • If this is being consumed by e.g. a reporting tool, it may be easier to compute the maximum as the results are being consumed. (Note, this doesn't just apply to reporting tools) Commented Jun 9, 2011 at 7:27

3 Answers 3

2
SELECT 
   (SELECT Max(StartDate) FROM myTable WHERE phName = "Name") as MaxDate, 
   id, name , phName , startDate, endDate
FROM myTable
WHERE phName = "Name"
Sign up to request clarification or add additional context in comments.

Comments

0

In Oracle you can use something like this:

select
    MAX(startDate) OVER(PARTITION BY phName),
    ID, name, phName, startDate, endDate
from table
where phName = 'Name';

Comments

0

The obvious solution is to use sub-queries but somewhat inneficient - particularly on MySQL (which does not handle push-predicates in sub-queries well).

Daniel Hilgarth's solution only works on Oracle.

For a generic, efficient solution (which unfortunately results in somewhat obfuascated code), see the max concat trick

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.