问题
I am having trouble selecting/inserting multiple max values with one script. The following table is made up to represent the combination of values with the tables I am trying to work with.
The script needs to be an insert statement to insert the returned values into a second table.
CREATE TABLE family
( state VARCHAR2(2 BYTE),
Birth date,
Married date,
Shirt size number(10 )
Shoe size number(10),
Hair VARCHAR2(80 BYTE),
carname VARCHAR2(24 BYTE),
CATname VARCHAR2(24 BYTE),
Hometown VARCHAR2(40 BYTE),
Alive CHAR(1 BYTE),
job_CATEGORY_1 VARCHAR2(40 BYTE),
job_CATEGORY_2 VARCHAR2(40 BYTE)
)
This table has over 1500 rows. I need to select all values from the records with the The combination of “Oldest birth date, oldest married date, largest shoe size and largest shirt size”. The remaining values need to be in the script.
When I select people with the oldest birth date, I get three records with various married dates, and various shirt and shoe size. My need is to select the combination of max(birth), max(married), max(shirt size) and max(shoe size), then include the remaining columns.
Any and all help will be greatly appreciated.
回答1:
You can do this with analytic functions:
select * from
(
select f.*,
rank() over (partition by state
order by birth) as birth_rank,
rank() over (partition by state, birth
order by married) as married_rank,
rank() over (partition by state, birth, married
order by shoe_size desc) as shoe_rank,
rank() over (partition by state, birth, married, shoe_size
order by shirt_size desc) as shirt_rank
from family f
)
where birth_rank = 1
and married_rank = 1
and shoe_rank = 1
and shirt_rank = 1;
But instead of select * in the outer query, select only the fields you're interested in - you probably don't want to see the rank fields.
Each _rank psuedocolumn is ranking the values in the matching column with the group of the preceding ones. So for birth_rank it's only looking at the state, and within each state there will be one or more records that get ranked as 1. For married_rank it's looking further down, so within each combination of state and birth date there will be one married date that is ranked as 1. And so on. The outer query then picks only the highest ranks, and there will usually only be one record per state. (Rank allows ties, so you may need a way to break ties if two or more records meet all the criteria).
The birth and married ranks are ordered ascending so the earliest data is ranked first; the show and shirt size ranks are ordered descending to the largest is ranked first.
SQL Fiddle demo, showing the ranks assigned to all the values for all rows in the first query, and then the filter applied in the second query so there is only one row (per state, though I've only included one). This is why sample data is useful.
来源:https://stackoverflow.com/questions/20525654/oracle-11g-selecting-inserting-multiple-max-values-with-one-script