PostgreSQL - Min Max条目

时间:2017-03-24 06:37:27

标签: postgresql

我有一个名为学生的视图,显示他们的姓名,学校,电话号码和开始日期,如下所示

select * from Students;

,结果如下

Name        |    School    |    Phone    |    Date_Started

Student A    Electrical Eng   0424477876      1/02/2008
Student B    Software Eng     0425432598      1/02/2008
Student C    Mathematics      0487639487      2/02/2012
Student D    Photovoltaic     0425588596      4/06/2012
Student G    Commerce         0425588692      6/08/2014

现在我需要创建一个视图,找出首先开始的学生以及根据开始日期开始的最后学生,并且应该产生以下输出

Started    |    Name    |    School    |    Date_Started
first        Student A   Electrical Eng     1/02/2008
first        Student B   Software Eng       1/02/2008
last         Student G   Commerce           6/08/2014      

因此,这需要一个新视图来使用已有的视图来实现这一目标。

我是postgreSQL的新手,并且尝试了一些似乎无法正常工作的案例陈述,感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

您可以使用窗口函数在单个语句中计算:

select *
from (
  SELECT case 
           when date_started = min(date_started) over () then 'first' 
           when date_started = max(date_started) over () then 'last'
         end as Started, 
         Name, School, Date_Started
  FROM Students 
) s 
where started in ('first', 'last')
order by date_started;

答案 1 :(得分:0)

您可以使用UNION来合并两个查询的结果。

SELECT 'first' Started, Name, School, Date_Started
FROM Students WHERE Date_Started = (SELECT MIN(Date_Started) FROM Students)
UNION
SELECT 'last' Started, Name, School, Date_Started
FROM Students WHERE Date_Started = (SELECT MAX(Date_Started) FROM Students)

答案 2 :(得分:0)

嗨你可以尝试这个ans

select 'First' as 'Started',* from student where Date_Started =(select min(Date_Started) from student)
union
select 'Last' as 'Started',* from student where Date_Started =(select max(Date_Started) from student)