sql用于满足条件的每个组中的一个条目

时间:2013-04-04 17:40:44

标签: mysql sql database

我有一个查询

SELECT ckt, setpt, clock FROM progs 
WHERE feed = "80302" AND day=4 AND clock<"12:15:00" 
ORDER BY ckt, clock DESC

这让我知道了:

ckt setpt clock
0 69  06:06:00
0 62  00:30:00
1 57  10:30:00
1 67  04:30:00
1 57  01:30:00
2 69  11:00:00
2 62  00:30:00

如何修改此查询以为每个CKT提供MAX(时钟)

总计: 每个cktday都有setptclock entries。我正在寻找(1或无)clock记录&lt;每个cktday的some_time。即

0 69  06:06:00
1 67  10:30:00
2 69  11:00:00
在mysql中

2 个答案:

答案 0 :(得分:4)

这样的东西?

SELECT ckt, MAX(setpt), MAX(clock)
FROM progs 
WHERE feed = "80302" AND day=4 AND clock<"12:15:00" 
GROUP BY ckt
ORDER BY ckt, clock DESC

<强>结果

| CKT | MAX(SETPT) |                     MAX(CLOCK) |
-----------------------------------------------------
|   0 |         69 | January, 01 1970 06:06:00+0000 |
|   1 |         67 | January, 01 1970 10:30:00+0000 |
|   2 |         69 | January, 01 1970 11:00:00+0000 |

See the demo

答案 1 :(得分:2)

听起来你需要JOIN表格自己加入MAX(clock)

SELECT p.ckt, p.setpt, p.clock 
FROM progs p
    JOIN (
        SELECT MAX(clock) maxClock, ckt
        FROM progs 
        WHERE feed = "80302" 
            AND day=4 
            AND clock<"12:15:00" 
        GROUP BY ckt
    ) p2 on p.ckt = p2.ckt AND p.clock = p2.maxclock
ORDER BY p.ckt, p.clock DESC

SQL Fiddle Demo(借鉴其他帖子)

产:

0   69  January, 01 1970 06:06:00+0000
1   57  January, 01 1970 10:30:00+0000
2   69  January, 01 1970 11:00:00+0000

请注意,ID为1的行与您想要的结果不同,但符合您问题的预期结果...