2

我有以下输入,其中用户以以下百分比(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
4

2 回答 2

3
select id, user, max(watched)
from tbl
group by id, user

我建议您将“watchedXX”更改为“XX”以便于计算。我上面的查询是基于这个假设

于 2013-06-20T07:58:43.167 回答
1

询问:

SQLFIDDLE示例

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 |
于 2013-06-20T10:37:41.413 回答