c1 c2 c3 c4 c5
"97" "12078602701" "ANSWERED" "334" "TIMECONDITION_16"
"98" "12078602701" "ANSWERED" "334" "333"
"105" "12078602702" "ANSWERED" "334" "TIMECONDITION_16"
"106" "12078602702" "ANSWERED" "334" "333"
"111" "14126061978" "ANSWERED" "279" "TIMECONDITION_16"
"113" "14126061978" "ANSWERED" "279" "265"
"120" "12078602703" "ANSWERED" "334" "TIMECONDITION_16"
"121" "12078602703" "ANSWERED" "334" "333"
"131" "12103306549" "NO ANSWER" "13" "TIMECONDITION_16"
"135" "12078602704" "ANSWERED" "334" "TIMECONDITION_16"
"136" "12078602704" "ANSWERED" "334" "333"
Consider the above rows in which it needs to be grouped by c2 and we have to give preference to column 5 value not having 'timecondition_16' but if no other value exists other than TIMECONDITION_16 only on that condition it should include row with TIMECONDITION_16. the expected result is
"98" "12078602701" "ANSWERED" "334" "333"
"106" "12078602702" "ANSWERED" "334" "333"
"113" "14126061978" "ANSWERED" "279" "265"
"121" "12078602703" "ANSWERED" "334" "333"
"131" "12103306549" "NO ANSWER" "13" "TIMECONDITION_16"
"136" "12078602704" "ANSWERED" "334" "333"
With NOT EXISTS
:
select t.* from tablename t
where c5 <> 'TIMECONDITION_16'
or not exists (
select 1 from tablename
where c2 = t.c2 and c5 <> 'TIMECONDITION_16'
)
See the demo .
Results:
| c1 | c2 | c3 | c4 | c5 |
| --- | ----------- | --------- | --- | ---------------- |
| 98 | 12078602701 | ANSWERED | 334 | 333 |
| 106 | 12078602702 | ANSWERED | 334 | 333 |
| 113 | 14126061978 | ANSWERED | 279 | 265 |
| 121 | 12078602703 | ANSWERED | 334 | 333 |
| 131 | 12103306549 | NO ANSWER | 13 | TIMECONDITION_16 |
| 136 | 12078602704 | ANSWERED | 334 | 333 |
In MySQL 8 you can use row_number()
. Partition by c2
and order by the Boolean expression c5 = 'TIMECONDITION_16'
. Each row for which this is true will come after all rows for which this is false as true is interpreted as 1 and false as 0 in that context. Filter for all rows where the row_number()
is 1. (You didn't specify any second criteria for the ordering so other than putting 'TIMECONDITION_16'
last a random row will be chosen.)
SELECT x.c1,
x.c2,
x.c3,
x.c4,
x.c5
FROM (SELECT t.c1,
t.c2,
t.c3,
t.c4,
t.c5,
row_number() OVER (PARTITION BY t.c2
ORDER BY t.c5 = 'TIMECONDITION_16') rn
FROM elbat t) x
WHERE x.rn = 1;
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.