2013-06-20 36 views
2

我有以下輸入,用戶在以下百分比(25或50或75或100)中觀看節目。我只想計算某個特定的百分比用戶在某個ID上。 輸入和輸出如下。如何根據mysql中的最高值合併輸出

輸入

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 

回答

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

我建議你改變 「watchedXX」 到 「XX」 更容易計算。我上面的查詢是基於這樣的假設

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 | 
相關問題