我有以下数据表,我从数据库中提取
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
我试图仅从每周的amount
列中提取最小值,因此该表应该是这样的
type week amount
a 201304 71
a 201305 77
谢谢你的帮助
答案 0 :(得分:2)
这个常规GROUP BY
有什么问题?
SELECT type, week, MIN(amount) amount
FROM table_name
GROUP BY type, week
如果您在同一周内使用相同数量的不同类型,您想做什么?如果你想知道一周内MIN(金额)的类型:
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
答案 1 :(得分:1)
尝试
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
这样做会将行号分配给您的分区,只需要一周和一个数量。您每周可能有很多金额。这会对它们进行编号,然后对它们进行排序,使最小值位于顶部(第1行)。你在where子句中得到这一行。无论类型如何,每周都会产生最低金额。
答案 2 :(得分:0)
您可以使用min和in子句
select * from my_table
where (amount, week ) in (
select min(amount), week from my_table group by week
);