按日期顺序选择不同的行

时间:2012-03-30 14:45:13

标签: sql

我有一张表(下方),我想选择。我想按照printorder进行分组,并按照lastsaved descending命令

Id  docid   printorder  lastsaved
1   1       1           2012-03-30 15:20:14.990
5   1       2           2012-03-30 15:20:15.733
9   1       1           2012-03-30 15:33:33.330

我认为这将是一个简单的查询,但我正在挣扎!如果有人能提供帮助那就太棒了

编辑以下是我一直在使用

的查询
SELECT DISTINCT(printorder), id, lastsaved, docid
FROM bpdocsides a
WHERE a.docid = 1
ORDER BY lastsaved DESC

4 个答案:

答案 0 :(得分:1)

所以你很清楚,你将无法通过printorder从该表和组中进行选择,除非你也按所有其他列进行分组,或者在剩余的列上使用某种聚合函数(MAX,SUM等) )。此外,如果您打算选择Id,您也可以从表中选择所有内容,因为列ID不会有任何重复记录。

换句话说:

select id, docid, printorder , lastsaved from table
group by printorder,docid,id,lastsaved 
order by lastsaved 

将等同于做

select id, docid, printorder , lastsaved 
from bpdocsides 
order by lastsaved

也许你真的想要这样的东西:

select docid, printorder , max(lastsaved)
from bpdocsides 
group by printorder,docid
order by max(lastsaved)

修改

你需要这个:

 select docid, printorder , max(lastsaved)
 from bpdocsides 
 group by printorder,docid
 where docid=1
 order by max(lastsaved)

答案 1 :(得分:0)

尝试以下内容:

SELECT DISTINCT printorder, id, lastsaved, docid
FROM bpdocsides a
WHERE a.docid = 1
ORDER BY lastsaved DESC

答案 2 :(得分:0)

我自己解决了这个问题。

select distinct docid, 
(select max(lastsaved) from bpdocsides a where a.docid = b.docid) from bpdocsides b

感谢您的帮助。

答案 3 :(得分:0)

您的代码适用于Postgre sql,有些类似于postgre。试试这个问题:

select 
     distinct on (printorder) Id, docid, printorder, lastsaved         
from 
     bpdocsides a 
where 
     a.docid = 1 
order by 
     lastsaved desc 

我添加了ON子句并删除了额外的逗号。同样,这只适用于PostgreSQL。其他数据库确实支持这种语法。

您可以尝试此查询,看看它是否适合您。如果你有一个主要的数据库系统它应该工作:

select b1.* from
(
    select             
        printorder, 
        max(lastsaved) as lastsaved
    from       
        bpdocsides
    group by printorder
) a1
join
(
    select 
        Id, 
        docid, 
        printorder, 
        lastsaved
    from 
        bpdocsides
    where       
        docid = 1 
) b1 on a1.printorder=b1.printorder and a1.lastsaved=b1.lastsaved