从结果中选择

时间:2013-11-25 02:04:30

标签: mysql select

有两个表

tracks(track_id,track_title)
track_rank(track_id,track_date_entered,track_position)

以下查询为我提供了包含重复次数的歌曲列表

SELECT
  tracks.track_title,
  track_rank.track_id,
  COUNT(track_rank.track_id) AS number_of_repetitions 
FROM
  tracks,
  track_rank 
WHERE
  track_rank.track_position = 1 
  AND track_rank.track_date_entered BETWEEN '1970-01-01' AND '1972-12-31' 
  AND tracks.track_id = track_rank.track_id 
GROUP BY
  track_rank.track_id 
ORDER BY
  number_of_repetitions DESC;

在执行上述查询后,任何人都可以帮助我如何从上面的结果中选择具有最高重复次数的曲目

2 个答案:

答案 0 :(得分:1)

对于AGGREGATE个函数ORDER BY,请使用:

 ORDER BY COUNT(track_rank.track_id) DESC

完整查询如下:

SELECT tracks.track_title,track_rank.track_id, COUNT(track_rank.track_id) AS  number_of_repetitions 
FROM tracks,track_rank 
WHERE track_rank.track_position = 1 AND track_rank.track_date_entered 
BETWEEN '1970-01-01' AND '1972-12-31' 
AND tracks.track_id = track_rank.track_id 
GROUP BY track_rank.track_id 
ORDER BY COUNT(track_rank.track_id) DESC;

答案 1 :(得分:1)

这是一个查询,它应该为您指定的过滤条件获得具有最高重复次数的曲目。这也将为您提供多个具有相同高音的音轨。重复。

     SELECT tracks.track_title,track_rank.track_id , COUNT(track_rank.track_id) AS number_of_repetitions FROM tracks,track_rank 
       where tracks.track_id=track_rank.track_id
       WHERE track_rank.track_position = 1 
       AND track_rank.track_date_entered BETWEEN '1970-01-01' AND '1972-12-31' AND 
    tracks.track_id = track_rank.track_id 
    GROUP BY track_rank.track_id 
    having COUNT(track_rank.track_id) =
    (
       SELECT 
    COUNT(track_rank.track_id) AS number_of_repetitions 
    FROM tracks,track_rank 
    where tracks.track_id=track_rank.track_id
    WHERE track_rank.track_position = 1 
    AND track_rank.track_date_entered BETWEEN '1970-01-01' AND '1972-12-31' 
    AND tracks.track_id = track_rank.track_id 
    GROUP BY track_rank.track_id 
    order by number_of_repetitions  desc
    limit 1
    );