[英]SQL Select min(date) group by with corresponding row
There are some subsets of a parent set with release date.父集的某些子集具有发布日期。 And I want the earliest release date with the subset's no, but in a group base.
我想要最早的发布日期和子集的编号,但在一个小组基础上。
I try this:我试试这个:
SELECT Sub_No,Parent_No,MIN(DATE)
FROM mytable
WHERE other_CODE IS NULL
GROUP BY Sub_No,Parent_No
ORDER BY Parent_No DESC
but I get this: but I only want the most earliest released one as the 2015-02-12's Sub_No and Parent_No.但我明白了:但我只想要最早发布的一个作为 2015-02-12 的 Sub_No 和 Parent_No。
Any help will be highly appreciated!任何帮助将不胜感激!
Parent_No (No column name) Sub_No
07 2015-02-12 90
07 2015-11-03 88
07 2017-02-06 59
You can use the NOT EXISTS
as follows:您可以按如下方式使用
NOT EXISTS
:
SELECT Sub_No,Parent_No,DATE
FROM mytable t
where other_CODE IS NULL
and not exists (select 1 from mytable tt
where tt.Parent_No = t.Parent_No and tt.date < t.date
and tt.other_CODE is null)
If your database supports analytical function then you can use it as follows:如果你的数据库支持解析function那么你可以使用如下:
select Sub_No,Parent_No, DATE from
(SELECT Sub_No,Parent_No, DATE,
row_number() over (partition by parent_no order by date) as rn
FROM mytable
WHERE other_CODE IS NULL) t
where rn = 1
Only if Parent_No and DATE are unique key of mytable, then you can do the trick like this:只有当 Parent_No 和 DATE 是 mytable 的唯一键时,你才可以这样做:
SELECT * FROM mytable
INNER JOIN
(
SELECT Parent_No,MIN(DATE) as MinDate
FROM mytable
WHERE other_CODE IS NULL
GROUP BY Parent_No
) AS Filter
on mytable.Parent_No = Filter.Parent_No and mytable.DATE = Filter.MinDate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.