根据名称分组,选择最大日期和最小日期的数据,并显示在一行上

在数据库中有个表aa

现在要根据名称分组,选择最大日期和最小日期的数据,并显示在一行上,

首先要根据名称分组,取得最大日期 然后 union all 根据名称分组,选取最小日期,效果如图

select top 100 percent aa.names,aa.s,aa.createdate from 
(
    (select   top 100 percent names,min(createdate) as 日期
    from aa
    group by names
    )
    union ALL
    (select   top 100 percent names,max(createdate) as 日期
    from aa
    group by names
    )
)t 
inner join aa on t.names=aa.names and t.日期=aa.createdate
order by t.names, t.日期

变成一行的话,要按名称查询,先查出最小数据,然后关联刚才的查询结果,条件是名称相等,日期不等

select t1.names,t1.s,t1.createdate,t2.s,t2.createdate from 
(
        select top 100 percent aa.names,aa.s,aa.createdate from 
        (
            select   top 100 percent names,min(createdate) as 日期
            from aa
            group by names    
        )t 
        inner join aa on t.names=aa.names and t.日期=aa.createdate
) t1
left join 
(
        select top 100 percent aa.names,aa.s,aa.createdate from 
        (
            (select   top 100 percent names,min(createdate) as 日期
            from aa
            group by names
            )
            union ALL
            (select   top 100 percent names,max(createdate) as 日期
            from aa
            group by names
            )
        )t 
        inner join aa on t.names=aa.names and t.日期=aa.createdate
)t2 on t1.names=t2.names and t1.createdate <> t2.createdate
order by t1.names

一定要用左联接,不然,只有一条的数据,就被过滤掉了。

原文地址:https://www.cnblogs.com/gates/p/4463862.html