zoukankan      html  css  js  c++  java
  • 根据名称分组,选择最大日期和最小日期的数据,并显示在一行上

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

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

  • 相关阅读:
    android11——Material Design
    android10——Internet
    Andrid09——Service
    Android08——MultiMedia
    Android07——ContentProvider
    Android06——Persistence
    <转>汇编源码调试
    编程中我犯过的错误一
    中国社会9大阶层划分,看看你在哪一层?
    汇编中如果汇编和调用API混合用的话要注意Pushad popad
  • 原文地址:https://www.cnblogs.com/gates/p/4463862.html
Copyright © 2011-2022 走看看