I have this data table below that I am pulling from a data base
type week amount
a 201304 77
a 201304 77
a 201304 77
a 201304 77
a 201304 71
a 201304 71
a 201305 77
a 201305 77
a 201305 77
a 201305 77
a 201305 77
a 201305 77
I am trying to pull only the minimum value from the amount
column for every week only, so that table should be like this
type week amount
a 201304 71
a 201305 77
Thank you for you help
What's wrong with this regular GROUP BY
?
SELECT type, week, MIN(amount) amount
FROM table_name
GROUP BY type, week
If you have different types in the same week with the same amount, what do you want to do? If you want to know what type has the MIN(amount) in a week:
SELECT DISTINCT t2.*
FROM
(SELECT week, MIN(amount) amount
FROM table_name
GROUP BY week) t1
JOIN table_name t2 ON t1.amount = t2. amount AND t1.week = t2.week
Try
Select type, week, amount
from
(Select type, week, amount, row_number () over(partition by week, amount order by amount asc) as rownumber
from table_name)
where rownumber = 1
What this does is assign row numbers to your partition of just week and amount. You may have many amounts per week. This numbers them and you sort them so that the smallest will be on top (row 1). You get just this row in the where clause. This will produce a minimum amount per week regardless of type.
You can use a min and in clause
select * from my_table
where (amount, week ) in (
select min(amount), week from my_table group by week
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.