Return multiple columns with a select max on only one
Frage
I want to write a SQL that returns multiple columns with a select max on one of them. Let me clearify with an example.
Practically I'd like to have something like this:
Select max(from_date)
,func_status_code
,name
from table
where from_date <= current date
So what I want is to perform a select max on a column but also get the other columns for that row/those rows.
from_date func_status_code name
2012-08-21 1 A
2012-08-21 4 A
2012-08-20 5 A
2012-08-20 3 A
returning
from_date func_status_code name
2012-08-21 1 A
2012-08-21 4 A
I know I could do a subselect, something like:
select from_date
,func_status_code
,name
from table
where from_date = (Select max(from_date)
from table
where from_date <= current date
)
But I can't understand why the other method doesn't work. Does anybody know how to achieve this?
Lösung
One way you can do this is with window/analytic functions:
select func_status_code, name
from (Select func_status_code, name,
max(from_date) over () as maxdate
from table
where from_date <= current date
) t
where from_date = maxdate
Andere Tipps
you lack GROUP BY
clause
SELECT from_date, MAX(func_status_code) maxCode, name
FROM tableName
-- WHERE from_date <= getDate() -- extra condition here
GROUP BY from_date, name
Your subselect query was correct. You could also achieve the same result with a common table expression.
WITH m as
(
Select max(from_date) mxdate
from table
where from_date <= current date
)
select from_date
,func_status_code
,name
from table t, m
where t.from_date = m.mxdate
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow