mysql查询仅返回未随时间变化的值

时间:2016-11-16 13:25:17

标签: mysql

我有一个类似

的表值
Id_indicator,   Value ,   date_data
1               2        01/10/2016
1               2        03/10/2016
1               3        04/10/2016
1               2        05/10/2016
2              21        06/10/2016
2              21        07/10/2016
2              21        08/10/2016
3              3         09/10/2016
3              4         10/10/2016
3              4         11/10/2016
4              4         12/10/2016

我需要查询该表,只需要获取id_indicator和count(number或id_indicator),其中值在该时间段内没有变化。

我尝试使用分组查询

select id_indicator, count(*), value  
from shrewd_db.indicator_status_history  
where  date_data between '2016-10-01 00:00:00' and '2016-10-01 10:59:59' 
group by id_indicator, value`;

现在很难获得像id_indicator = 2value =21max (date_data) = 08/10/2016

这样不变的价值

2 个答案:

答案 0 :(得分:1)

<强> SQL Fiddle Demo

我必须更改日期范围,否则只有第一行会包含它

SELECT `Id_indicator`, COUNT(*), max(value) as value
FROM Table1
WHERE  `date_data` between '2016-10-01 00:00:00' and '2016-10-13 10:59:59'
GROUP BY `Id_indicator`
HAVING max(value) = min(value)

<强>输出

此结果还将包含仅有一条记录的指标,其中显然无法更改值。您可能需要添加HAVING COUNT(*) > 1来删除这些

enter image description here

答案 1 :(得分:0)

如果我理解正确,并且您希望VAL所记录的所有计数从记录变为记录:

SELECT p.id_indicator,count(*) as cnt
FROM (
    SELECT t.id_indicator,
           t.value
           (SELECT s.value FROM YourTable s
            WHERE s.id_indicator = t.id_indicator 
              AND s.date_data between '2016-10-01 00:00:00' and '2016-10-01 10:59:59' 
              AND s.date_data < t.date_data
            ORDER BY s.date_data DESC
            LIMIT 1) as last_val
    FROM YourTable t
    WHERE t.date_data between '2016-10-01 00:00:00' and '2016-10-01 10:59:59' ) p
WHERE p.val = p.last_val
GROUP BY p.id_indicator;

如果您只想要那些在VAL没有改变的整个时期内的那些更改,那么它会更容易:

select id_indicator, count(*),max(DATE_DATA) 
from shrewd_db.indicator_status_history  
where  date_data between '2016-10-01 00:00:00' and '2016-10-01 10:59:59' 
group by id_indicator
HAVING MAX(VALUE) = MIN(VALUE);