2014-04-29 45 views
2

一個記錄這是我的原始數據: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 

在原始數據,有兩個記錄嘗試9, 10,11和14.我需要一個查詢Value字段的查詢,如果它是一個數字,那麼將「挑選」該記錄的值爲「suspend」。

我試圖用一組由查詢,如:

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

但是這不是我所需要的,因爲最大(時間)不符合分鐘(價值)。我需要原始的價值,時間對。

任何人都可以幫助我解決這個問題嗎?

回答

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

這是解決方案,我會去,這在我看來是最快的:

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` 
+0

這似乎並沒有這樣做。 http://sqlfiddle.com/#!2/94c3e/3 –

+0

固定!現在試試 ! :) –

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;