代码之家  ›  专栏  ›  技术社区  ›  theShingles

SQL排序方式和“不太多组”

  •  0
  • theShingles  · 技术社区  · 16 年前

    假设我有一张桌子: -------------------------------------- |ID|日期|组|结果| -------------------------------------- |1|01/06|第1组|12345| |2005年1月2日|第2组|54321| |2004年1月3日|第1组|11111| --------------------------------------

    我想按顶部的最新日期对结果进行排序,但将“组”列分组在一起,但仍然有不同的条目。我想要的结果是:

    1 | 01/06 | Group1 | 12345
    3 | 01/04 | Group1 | 11111
    2 | 01/05 | Group2 | 54321
    

    编辑:

    我正在使用MSSQL。我将研究将oracle查询转换为MS SQL并报告我的结果。

    编辑

    SQL Server 2000,因此不支持OVER/PARTITION=[

    非常感谢。

    4 回复  |  直到 16 年前
        1
  •  1
  •   David    16 年前

    您应该指定您使用的RDBMS。这个答案适用于Oracle,可能不适用于其他系统。

    SELECT * FROM table
    ORDER BY MAX(date) OVER (PARTITION BY group) DESC, group, date DESC
    
        2
  •  2
  •   Dave Costa    16 年前
    declare @table table (
        ID int not null,
        [DATE] smalldatetime not null,
        [GROUP] varchar(10) not null,
        [RESULT] varchar(10) not null
    )
    
    insert @table values (1, '2009-01-06', 'Group1', '12345')
    insert @table values (2, '2009-01-05', 'Group2', '12345')
    insert @table values (3, '2009-01-04', 'Group1', '12345')
    
    
    select t.*
    from @table t
    inner join (
        select 
            max([date]) as [order-date],
            [GROUP]
        from @table orderer
        group by
            [GROUP]
    ) x
        on t.[GROUP] = x.[GROUP]
    order by
        x.[order-date] desc,
        t.[GROUP],
        t.[DATE] desc
    
        3
  •  1
  •   akf    16 年前

    使用a order by 带有两个参数的子句:

    ...order by group, date desc
    

        4
  •  0
  •   Mark Schultheiss    16 年前
    SELECT table2.myID,
     table2.mydate, 
     table2.mygroup, 
     table2.myresult
    FROM (SELECT DISTINCT mygroup FROM testtable as table1) as grouptable
    JOIN testtable as table2
     ON grouptable.mygroup = table2.mygroup
    ORDER BY grouptable.mygroup,table2.mydate
    

    抱歉,我无法使用保留名称的列,请重命名这些列以使其正常工作:)