2
select
    id,
    attempt,
    question,
    att_number,
    answer,
    timestamp,
    event
from
    mytable

在 MSSQL 2008 R2 中给了我这个输出:

id,attempt,question,seq_number,answer,timestamp,event
1296040,22059,3813,0,"11960,11961,11959,11958:",1265006717,0
1296165,22059,3813,1,"11960,11961,11959,11958:11960",1265011083,2
1296166,22059,3813,1,"11960,11961,11959,11958:11960",1265011049,6
1296163,22059,3813,1,"11960,11961,11959,11958:11960",1265011037,6
1296164,22059,3813,1,"11960,11961,11959,11958:11960",1265011072,6

如何只为尝试、问题、att_number、答案和事件列选择唯一的行,并且时间戳列的值为最低?

我要这个:

id,attempt,question,seq_number,answer,timestamp,event
1296040,22059,3813,0,"11960,11961,11959,11958:",1265006717,0
1296165,22059,3813,1,"11960,11961,11959,11958:11960",1265011083,2
1296163,22059,3813,1,"11960,11961,11959,11958:11960",1265011037,6
4

5 回答 5

2

您可以使用排名功能

with cte as(
    select id,attempt,question,att_number,answer,timestamp,event,
           rn = Row_Number() Over (
                    Partition By attempt, question, att_number, answer,event 
                    Order By timestamp Asc)
    from mytable
)
select select,id,attempt,question,att_number,answer,timestamp,event
from cte
where rn = 1

如果您希望每组具有最低时间戳的所有记录替换Row_NumberDense_Rank.

于 2013-07-25T10:52:10.227 回答
1

您需要将 GROUP BY 与 MIN 一起使用:

select MIN(id),
       attempt,
       question,
       seq_number,
       answer,
       MIN(timestamp),
       event
  from mytable
  GROUP BY ATTEMPT, QUESTION, SEQ_NUMBER, ANSWER, EVENT

从这个问题来看并不明显,但 OP 同时需要 MIN(ID) 和 MIN(TIMESTAMP)。另请注意,示例结果中的列名与 OP 的 SQL 中的列名不同。我选择接受seq_number示例中的结果与原始 SELECT 语句中的结果相同att_number

SQLFiddle 在这里

分享和享受。

于 2013-07-25T10:46:53.333 回答
1
select
id,
attempt,
question,
att_number,
answer,
timestamp,
event
from
mytable m 
where m.timestamp=(
    select min(timestamp) 
    from mytable mi 
    where mi.attempt=m.attempt and mi.question=m.question and mi.att_number=m.att_number and mi.answer=m.answer and mi.event=m.event
)
于 2013-07-25T10:49:41.830 回答
1

你必须使用group by子句。

以下select语句适用于您的示例。

select        
    min(id), attempt,question,
    att_number, answer, timestamp,
    event
from
    mytable
group by 
    attempt,question,
    att_number, answer, timestamp,
    event

但是如果你真的想要最低的时间戳,你必须删除id列形式select如下

select         
    attempt,question,
    att_number, answer, min(timestamp),
    event
from
    mytable
group by 
    attempt,question,
    att_number, answer,
    event
于 2013-07-25T10:42:55.737 回答
-1

使用 distinct 和 order by 语句。

于 2013-07-25T10:45:49.003 回答