select count Max(value)with where

时间:2016-03-08 12:52:47

标签: php mysql

您好,请参阅附表中我想使用此查询提取数据的表格

SELECT count(idmilestone) 
FROM  milestoneevent 
WHERE max(idmilestone=1)

我想要计算所有带有最后里程碑= 1的文件,在我的情况下它必须返回5因为两个文件的里程碑现在是2请帮我实现

enter image description here

6 个答案:

答案 0 :(得分:2)

对于您提供的数据,里程碑正在增加数字。如果这通常是真的,你可以简单地做:

select count(*)
from (select idfile, max(idmilestone) as max_idmilestone
      from milestoneevent
      group by idfile
     ) m
where max_idmilestone = 1;

或者,您可以使用dat来定义最后一个:

select count(*)
from milestonemevent me
where me.dat = (select max(me2.dat)
                from milestonemevent me2
                where me.idfile = me2.idfile
               ) and
      me.idmilestone = 1;

答案 1 :(得分:1)

试试这个

SELECT count(idmilestone) 
FROM  milestoneevent 
WHERE idfile NOT IN(SELECT idfile 
    FROM milestoneevent 
    WHERE idfile > 1)

答案 2 :(得分:1)

请试试这个,它会给出idmilestone的计数,即最小的一个,即1.

SELECT count(idmilestone) FROM  milestoneevent 
WHERE idmilestone =(SELECT MIN(idmilestone) FROM milestoneevent)

如果你想要count等于1,那么试试这个

SELECT count(idmilestone) FROM  milestoneevent 
WHERE idmilestone =1

答案 3 :(得分:1)

您可以使用LEFT JOIN

SELECT t1.id, t1.idfile, t1.idmilestone
FROM milestoneevent AS t1
LEFT JOIN milestoneevent AS t2 
   ON t1.idfile = t2.idfile AND  t1.dat < t2.dat  
WHERE t1.idmilestone = 1 AND t2.id IS NULL

Demo here

计算使用COUNT

SELECT COUNT(*)
FROM milestoneevent AS t1
LEFT JOIN milestoneevent AS t2 
   ON t1.idfile = t2.idfile AND  t1.dat < t2.dat  
WHERE t1.idmilestone = 1 AND t2.id IS NULL
GROUP BY t1.idfile 

答案 4 :(得分:1)

试试这个:

SELECT COUNT(*) 
FROM (
    SELECT idmilestone
    FROM milestoneevent 
    GROUP BY idmilestone
    HAVING COUNT(*) = 1
)
WHERE idmilestone=1

答案 5 :(得分:0)

select count('id')
from (select idfile, max(idmilestone) as max_idmilestone
      from milestoneevent
      group by idfile
     ) d
where max_idmilestone = 1;