SQL选择一个记录而不是另一个

时间:2014-04-29 20:24:13

标签: mysql sql

这是我的原始资料:

Attempt Value   Time
1       suspend 1391685762
2       suspend 1391686288
3       suspend 1391686413
4       suspend 1392648082
5       suspend 1392648230
6       suspend 1393255593
7       suspend 1393255953
8       suspend 1393257567
9       suspend 1393257738
9       75      1393341840
10      suspend 1393359336
10      62      1393361876
11      suspend 1393422454
11      87      1393425173
12      suspend 1394622268
13      suspend 1394622275
14      suspend 1394622304
14      85      1394623834
15      suspend 1394622379
16      suspend 1394622441
17      suspend 1394622543
18      suspend 1394622785
19      suspend 1394622968
20      suspend 1394623375

这是我的目标查询结果:

Attempt Value   Time
1       suspend 1391685762
2       suspend 1391686288
3       suspend 1391686413
4       suspend 1392648082
5       suspend 1392648230
6       suspend 1393255593
7       suspend 1393255953
8       suspend 1393257567
9       75      1393341840
10      62      1393361876
11      87      1393425173
12      suspend 1394622268
13      suspend 1394622275
14      85      1394623834
15      suspend 1394622379
16      suspend 1394622441
17      suspend 1394622543
18      suspend 1394622785
19      suspend 1394622968
20      suspend 1394623375

在原始数据中,Attempts 9,10,11和14有两条记录。我需要一个查看Value字段的查询,如果它是一个数字,那么" picks&#34 ;记录值为&#34的那个;暂停"。

我尝试使用像查询一样的小组:

SELECT Attempt, min(Value), max(Time)
FROM t
GROUP BY Attempt

但这不是我需要的,因为max(Time)与min(Value)不对应。我需要原始的价值,时间对。

有人可以帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:3)

您可以使用子查询来实现此结果。

SELECT Attempt, 
    min(Value) as Value,
    (SELECT Time FROM t as t1 
     WHERE t1.Value = min(t.Value) 
         AND t.Attempt = t1.Attempt) as Time
FROM t as t
GROUP BY Attempt

答案 1 :(得分:1)

这是我想要的解决方案,在我看来这是最快的:

SELECT DISTINCT(`attempt`) as `attempt`,
   IF(MAX(`value`)=0,'suspend',MAX(`value`)) as `value`, `time`
FROM(
   SELECT `attempt`, IF(`value`='suspend',0,`value`) as `value`, `time`
   FROM `t`
) as `a`
GROUP BY `attempt`

答案 2 :(得分:1)

这是一个使用连接的选项。以下查询将提供更好的性能。

SELECT 
DISTINCT
COALESCE(tin.Attempt, t.Attempt) Attempt, COALESCE(tin.Value, t.value) Value, COALESCE(tin.Time, t.time) Time
FROM t
LEFT OUTER JOIN
(SELECT 
    Attempt, Value, Time
 FROM t
WHERE Value <> 'suspend') tin
ON t.Attempt = tin.Attempt AND t.Value <> tin.Value;