Sql 在GROUPBY子句中使用min和max
我想要以下oracle sql中的输出 我的数据如下表所示:Sql 在GROUPBY子句中使用min和max,sql,oracle,oracle11g,Sql,Oracle,Oracle11g,我想要以下oracle sql中的输出 我的数据如下表所示: id start_date end_date assignment number 1 2.02.2014 15.02.2014 10 2 25.02.2014 30.02.2014 20 3 26.03.2014 04.05.2014 30 4 06.06.2014 31.12.4712 10 我需要使用分组
id start_date end_date assignment number
1 2.02.2014 15.02.2014 10
2 25.02.2014 30.02.2014 20
3 26.03.2014 04.05.2014 30
4 06.06.2014 31.12.4712 10
我需要使用分组输出
assignment_number start_date end_date
10 02.02.2014 15.02.2014
10 06.06.2014 31.12.4712
20 25.02.2014 30.02.2014
30 26.03.2014 04.05.2014
我试着使用最小值(开始日期)和最大值(结束日期)作为任务10的输出
assignment_number start_date end_date
10 02.02.2014 31.12.4712
但我想:-
assignment_number start_date end_date
10 02.02.2014 15.02.2014
10 06.06.2014 31.12.4712
请帮忙我想你必须分别计算最小值和最大值,然后合并它们。试着这样做:
SELECT
assignment_number
, start_date
, end_date
FROM
(SELECT
assignment_number
, start_date
, end_date
FROM TABLE
GROUP BY assignment_number
HAVING MIN(start_date)
UNION
SELECT
assignment_number
, start_date
, end_date
FROM TABLE
GROUP BY assignment_number
HAVING MAX(end_date)
)
ORDER BY
1 ASC
, 2 ASC
, 3 ASC
)
就目前而言,您的需求没有真正意义。您需要为每个赋值指定min()和max()(在这种情况下,您的结果是正确的),或者需要表格中的每一行(在这种情况下,您根本不需要
分组依据
)。请提供有关预期输出的更多信息。
select id, to_char(start_date,'dd.mm.yyyy') start_date, to_char(end_date,'dd.mm.yyyy') end_date,ASSIGNMENT_NUMBER from sof1 s
where not exists
(select 1 from sof1 s2
where s2.assignment_number=s.assignment_number
and s2.start_date<s.start_date
)
or not exists
(select 1 from sof1 s2
where s2.assignment_number=s.assignment_number
and s2.end_date>s.end_date
)
order by ASSIGNMENT_NUMBER
select id, to_char(start_date,'dd.mm.yyyy') start_date, to_char(end_date,'dd.mm.yyyy') end_date,ASSIGNMENT_NUMBER from
(select s.*
, min (start_date) over (partition by ASSIGNMENT_NUMBER) sd
, max (end_date) over (partition by ASSIGNMENT_NUMBER) ed
from sof1 s
)
where start_date=sd or end_date=ed
order by ASSIGNMENT_NUMBER, start_date