gate_s

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 

在数据库中有个表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

 

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

 

posted on 2015-04-28 19:22  gate_s  阅读(1026)  评论(0编辑  收藏  举报