簡體   English   中英

基於Max()的SELECT和GROUP BY多列

[英]SELECT and GROUP BY multiple columns based on Max()

當前表事件:

|  eventId  |  personId  |  type  | title   |  score  |
+-----------+------------+--------+---------+---------+
| 1         | 1          | movie  | Mission | 12      |
| 2         | 1          | movie  | UNCLE   | 32      |
| 3         | 1          | show   | U2      | 17      |
| 4         | 1          | show   | Leroy   | 13      |
| 5         | 2          | movie  | Holmes  | 19      |
| 6         | 2          | movie  | Compton | 14      |
| 7         | 2          | show   | Imagine | 22      |
| 8         | 2          | show   | Kane    | 22      |

MySQL示例:

SELECT @personId:=personId as personId,
(
  SELECT title FROM Events 
  WHERE rate = (SELECT MAX(score) FROM Events) 
  AND type = ‘movie’ AND personId=@personId
) as movie,
(
  SELECT title FROM Events 
  WHERE rate = (SELECT MAX(score) FROM Events) 
  AND type = ‘movie’ AND personId=@personId
) as show,
FROM Events
GROUP BY personId
ORDER BY personId;

所需輸出:

|  personId  |  movie   |  show   |
+------------+----------+---------+
| 1          | UNCLE    | U2      |
| 2          | Holmes   | Imagine |

理想的結果是顯示電影的MAX()分數,並在“事件”表中顯示每個personId。 我的實際輸出包含NULLS,並且加載時間很長。 我的實際事件表大約有20,000個條目。

UPDATE解決方案(源自前兩個答案以提高性能)

SELECT e.personId,
(
  SELECT o.title 
  FROM Events o
  LEFT JOIN Events b 
      ON o.personId = b.personId AND o.score < b.score
      AND o.type = b.type
  WHERE o.type = 'movie' AND o.personId=e.personId  LIMIT 1
) as best_movie ,
(
  SELECT o.title
  FROM Events o
  LEFT JOIN Events b 
      ON o.personId = b.personId AND o.score < b.score
      AND o.type = b.type
  WHERE o.type = 'show' AND o.personId=e.personId  LIMIT 1
) as best_show
FROM Events e
GROUP BY e.personId
ORDER BY e.personId

我不確定這是否正是您所需要的。

但是只是我的猜測,可能您不需要多個列?

http://sqlfiddle.com/#!9/04b27/4

SELECT e.* 
FROM `events` e
left join `events` e1
on e.type = e1.type
and e.score<e1.score
WHERE e1.eventId IS NULL
GROUP BY personId, type, score

更新如果您需要每人+類型的最高分數,可以

http://sqlfiddle.com/#!9/04b27/13

SELECT e.* 
FROM `events` e
left join `events` e1
on e.personId = e1.personId
and e.type = e1.type
and e.score<e1.score
WHERE e1.eventId IS NULL
GROUP BY personId,  score

我對您的查詢做了一些修改。

看一看:

SELECT @personId:=personId as personId,
(
  SELECT title FROM Events
  WHERE score = (SELECT MAX(score) FROM Events WHERE type = 'movie' 
  AND personId=@personId) 
  AND type = 'movie' AND personId=@personId  LIMIT 1
) as movie ,
(
  SELECT title FROM Events
  WHERE score = (SELECT MAX(score) FROM Events WHERE type = 'show' 
  AND personId=@personId) 
  AND type = 'show' AND personId=@personId  LIMIT 1
) as show1 
FROM Events
GROUP BY personId
ORDER BY personId

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM