分组而不是分组列?

时间:2015-07-12 02:38:55

标签: sql group-by

有这个查询:

SELECT brand, 
       ROUND(AVG(rating), 0) AS ar, 
       model
FROM engines
WHERE rating IS NOT NULL
AND rating != ''
AND category='Road'
GROUP BY brand
ORDER BY atr DESC

问题是模型列。

如何使结果显示评分最高的模型? (目前它只显示与过滤器匹配的第一个模型)。

即。如果数据是:

brand1, model1, 3
brand1, model2, 5
brand1, model3, 4

如何使结果如下:

brand1, 4, model2

(因为model2的评分最高,为5)

谢谢!

2 个答案:

答案 0 :(得分:1)

<script type="text/javascript"> function centerGalleryOverlay(){ var top = ($('.image-container').height() / 2).toFixed() ; $('.image-container').css('marginTop', '-' + top + 'px'); var left = ($('.image-container').width() / 2).toFixed() ; $('.image-container').css('marginLeft', '-' + left + 'px'); } $(document).ready(function(){ var galleryTitle = null; $('.cm-gallery').click(function(e){ e.preventDefault(); galleryTitle = $(this).data('gallery'); $('.gallery-overlay .image-container img').attr( 'src', $(this).attr('href') ); $('.gallery-overlay').fadeIn(500); centerGalleryOverlay(); var galleryItems = null; galleryItems = []; $('.cm-gallery').each(function(){ if($(this).data('gallery') == galleryTitle){ galleryItems.push($(this).attr('href')) } }); var currentIndex = null; currentIndex = 0; if(galleryItems.length > 0){ $('.gallery-overlay .image-container .gallery-next').show(); } $('.gallery-overlay .image-container .gallery-next').click(function(){ currentIndex = currentIndex + 1; console.log(currentIndex); if(currentIndex >= (galleryItems.length - 1) ){ $('.gallery-overlay .image-container .gallery-next').hide(); } $('.gallery-overlay .image-container .gallery-prev').show(); $('.gallery-overlay .image-container img').attr( 'src', galleryItems[currentIndex] ); }) $('.gallery-overlay .image-container .gallery-prev').click(function(){ currentIndex = currentIndex - 1; console.log(currentIndex); if(currentIndex <= 0 ){ $('.gallery-overlay .image-container .gallery-prev').hide(); } $('.gallery-overlay .image-container .gallery-next').show(); $('.gallery-overlay .image-container img').attr( 'src', galleryItems[currentIndex] ); }) }) $('.gallery-overlay .gallery-close').click(function(){ $('.gallery-overlay').hide(); galleryItems = null; currentIndex = null; galleryTitle = null; }); }) </script> 中,您可以执行此操作。

sql server

SELECT brand, Round(Avg(rating), 0) AS ar, Model = (SELECT TOP 1 E.model FROM engines E ORDER BY rating DESC) FROM engines WHERE rating IS NOT NULL AND rating != '' AND category = 'Road' GROUP BY brand ORDER BY atr DESC 中将子查询更改为

mysql

答案 1 :(得分:1)

标准SQL将是:

select e.*
from (select e.*, row_number() over (partition by brand order by rating desc) as seqnum
      from engines e
     ) e
where seqnum = 1;

没有窗口功能的替代方案是:

select e.*
from engines e join
     (select brand, max(rating) as maxr
      from engines
      group by brand
     ) ee
     on e.brand = ee.brand and e.rating = ee.rating;