This is my Original Data:
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
And this is my Target Query Result:
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
In the original data, there are two records for Attempts 9, 10, 11, and 14. I need a query that looks at the Value field, if it's a number, then "picks" that record over the one with a value of "suspend".
I tried using a group by query like:
SELECT Attempt, min(Value), max(Time)
FROM t
GROUP BY Attempt
But this is not what I needed because max(Time) does not correspond to min(Value). I need the original Value, Time pair.
Can anyone help me with this query?
You could use a sub query to achieve this result.
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
This is the solution I'd go for, which would in my opinion be the fastest:
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`
Here is an option using joins. The following query will render better performance.
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.