码迷,mamicode.com
首页 > 编程语言 > 详细

对数据按组排序

时间:2015-09-03 14:03:26      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

数据库环境:SQL SERVER 2005

  有数据如图1,字段id是序号,id相同的为一组,createtime为创建时间。要求:

将createtime为最新时间所在的组排在前面,同时,同一组内的数据按createtime降序排序。

最终结果如图2所示

技术分享    技术分享    技术分享

  实现思路:

  1.用分析函数取组内最大值

  2.按照组内最新时间和创建时间降序排序

  SQL实现:

技术分享
/*测试数据*/
WITH    x0
          AS ( SELECT   1 AS id ,
                        100 AS data ,
                        CONVERT(DATETIME, 2015-09-01 12:23:56) AS createtime
               UNION ALL
               SELECT   1 AS id ,
                        24 AS data ,
                        CONVERT(DATETIME, 2015-09-02 18:25:26) AS createtime
               UNION ALL
               SELECT   2 AS id ,
                        68 AS data ,
                        CONVERT(DATETIME, 2015-09-01 08:46:12) AS createtime
               UNION ALL
               SELECT   2 AS id ,
                        360 AS data ,
                        CONVERT(DATETIME, 2015-09-01 00:52:58) AS createtime
               UNION ALL
               SELECT   2 AS id ,
                        200 AS data ,
                        CONVERT(DATETIME, 2015-09-03 10:08:36) AS createtime
               UNION ALL
               SELECT   3 AS id ,
                        70 AS data ,
                        CONVERT(DATETIME, 2015-09-02 13:48:12) AS createtime
               UNION ALL
               SELECT   4 AS id ,
                        108 AS data ,
                        CONVERT(DATETIME, 2015-08-31 03:11:23)
             ),/*分析函数求组内最新时间*/
        x1
          AS ( SELECT   id ,
                        data ,
                        createtime ,
                        MAX(createtime) OVER ( PARTITION BY id ) AS createtime_max
               FROM     x0
             )/*对结果集排序*/
    SELECT  id ,
            data ,
            createtime
    FROM    x1
    ORDER BY createtime_max DESC ,
            createtime DESC
            
View Code

(本文完)

对数据按组排序

标签:

原文地址:http://www.cnblogs.com/boss-he/p/4780088.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!