我有以下输入,其中用户以下列百分比(25或50或75或100)观看节目。我只想计算某个用户在特定ID上观看的最高百分比。 输入和输出如下所示。
输入
id1, u1, watched25
id2, u1, watched25
id1, u1, watched50
id1, u1, watched75
id3, u1, watched25
id4, u1, watched25
id1, u1, watched100
id2, u1, watched50
id5, u1, watched25
id5, u1, watched50
id5, u1, watched75
id5, u1, watched100
id1, u2, watched25
id1, u2, watched50
id3, u2, watched25
id3, u3, watched25
id1, u2, watched75
id4, u3, watched25
id4, u3, watched50
期望的输出
id1, u1, watched100
id2, u1, watched50
id3, u1, watched25
id5, u1, watched25
id5, u1, watched100
id1, u2, watched75
id3, u2, watched25
id3, u3, watched25
id4, u3, watched50
答案 0 :(得分:3)
select id, user, max(watched)
from tbl
group by id, user
我建议您将“watchedXX”更改为“XX”以便于计算。我上面的查询是基于这个假设
答案 1 :(得分:1)
查询:
<强> SQLFIDDLEEXample 强>
SELECT t1.id1,
t1.u1,
MAX(CAST(REPLACE(t1.watched25, 'watched', '') AS SIGNED)) as watched
FROM Table1 t1
GROUP BY t1.id1, t1.u1
结果:
| ID1 | U1 | WATCHED |
----------------------
| id1 | u1 | 100 |
| id1 | u2 | 75 |
| id2 | u1 | 50 |
| id3 | u1 | 25 |
| id3 | u2 | 25 |
| id3 | u3 | 25 |
| id4 | u1 | 25 |
| id4 | u3 | 50 |
| id5 | u1 | 100 |
所需的输出查询:
SELECT t1.id1,
t1.u1,
CONCAT('watched',MAX(CAST(REPLACE(t1.watched25, 'watched', '') AS SIGNED))) as watched
FROM Table1 t1
GROUP BY t1.id1, t1.u1
结果所需的输出:
| ID1 | U1 | WATCHED |
-------------------------
| id1 | u1 | watched100 |
| id1 | u2 | watched75 |
| id2 | u1 | watched50 |
| id3 | u1 | watched25 |
| id3 | u2 | watched25 |
| id3 | u3 | watched25 |
| id4 | u1 | watched25 |
| id4 | u3 | watched50 |
| id5 | u1 | watched100 |