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
如何仅为timestamp列的LOWEST值选择try,question,att_number,answer和event列的唯一行?
我想要这个:
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
答案 0 :(得分:2)
您可以使用ranking function:
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_Number
替换为Dense_Rank
。
答案 1 :(得分: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
答案 2 :(得分: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
相同。
分享并享受。
答案 3 :(得分: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
)
答案 4 :(得分:-1)
使用distinct和order by statement。