使用WHERE和GROUP BY获取最低值的完整行

时间:2014-02-21 00:53:25

标签: mysql sql group-by min

我想显示一个预览页面,其中每张图片组的图片位置最低,在线= Y. 加。我想在线获取该组的总图片(如果可能的话)

我有一张图片库的下表:

PicID(autoinc) | PicGrp(INT) | Online(Y|N) | Pos(0-10,unique within Grp) | ... | Description

1 | 1 | Y | 0
2 | 1 | Y | 1
3 | 2 | N | 1
4 | 2 | N | 3
5 | 2 | Y | 7
6 | 2 | Y | 2
7 | 2 | Y | 10

所以我想:

1 | 1 | Y | 0 | ... | Description | Total(2)
6 | 2 | Y | 2 | ... | Description | Total(3)

一个方向......当然不工作: - )

SELECT PictureID, COUNT(*) AS Total 
FROM Pictures 
WHERE MIN(Position) AND Online = 'Y' 
GROUP BY PictureGroup

1 个答案:

答案 0 :(得分:0)

很确定这就是你想要的:

select y.picid, y.picgrp, y.online, y.pos, count(z.picid) as total
  from pictures y
  join pictures z
    on y.picgrp = z.picgrp
   and y.online = z.online
 where y.pos = (select min(x.pos)
                  from pictures x
                 where x.picgrp = y.picgrp
                   and x.online = 'Y')
   and y.online = 'Y'
 group by y.picid, y.picgrp, y.online, y.pos