简体   繁体   中英

Get full row for lowest value with WHERE AND GROUP BY

I would like to display a preview page with 1 picture of each picturegroup with the lowest position and Online=Y add. I would like to get the total pictures online for the group (if possible)

I have the following table for a Picture Gallery:

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

So I would like to have:

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

One Direction..not working, of course:-)

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

Pretty sure this is what you want:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM