我试图根据最短日期返回一行,但不会带回日期字段

时间:2017-11-09 16:06:31

标签: sql oracle greatest-n-per-group

select customer_id, street_address, city, state, zip  
from customer  where min(date);  

3 个答案:

答案 0 :(得分:0)

如果Teradata:

select customer_id, street_address, city, state, zip from customer 
qualify row_number() over(partition customer_id order by date)=1

其他选择:

select customer_id,street_address, city, state, zip from customer a
inner join (select customer_id, min(date) as min_date from customer group by customer_id) b
on a.customer_id=b.customer_id and a.date=b.min_date

答案 1 :(得分:0)

考虑到你在T-SQL中尝试这个。您可以尝试使用CTE(公用表表达式)

示例:

select 'a123' street_address, 'as' city,'ap' state, 123456 zip, cast(getdate()-10 as date) [day] into #temp
insert into #temp values('b12','ad','aw',345478,cast(getdate()-1 as date))
insert into #temp values('c243','a2','a3',3458,cast(getdate()-12 as date))
insert into #temp values('e3d','a2','af',8324,cast(getdate()-13 as date))
insert into #temp values('f46','a3','ag',337,cast(getdate()-13 as date))
insert into #temp values('g23','a4','ah',0374,cast(getdate()-1 as date))
insert into #temp values('h12','af','aj',946,cast(getdate()-17 as date))
insert into #temp values('634','ad','a8',345,cast(getdate()-17 as date))

select * from #temp

--Query to return min valued row
;with q as (select min(day) minday from #temp)
select street_address, city, state, zip from #temp t cross apply q where t.day=q.minday

为CTE阅读的博客:        https://www.red-gate.com/simple-talk/sql/t-sql-programming/sql-server-cte-basics/

答案 2 :(得分:0)

在每个rdbms中最简单的解决方案是:

select customer_id, street_address, city, state, zip 
from customer 
where date in (select min(date) from customer)
;