1

我们从一组传感器读取值,偶尔会丢失一个或两个特定传感器的读数,所以我不时运行查询以查看所有传感器是否具有相同的记录计数。

GROUP BY sensor_id HAVING COUNT(*) != xxx;

所以我运行一次查询以直观地获得 xxx 的值,然后再次运行它以查看是否有任何变化。

但是有什么聪明的方法可以在单个查询中自动执行此操作吗?

4

2 回答 2

2

你可以这样做:

HAVING COUNT(*) != (SELECT MAX(count) FROM (
  SELECT COUNT(*) AS count FROM my_table GROUP BY sensor_id
) t)

或者按每组中的计数再次分组(并忽略第一个结果):

SELECT count, GROUP_CONCAT(sensor_id) AS sensors
FROM (
  SELECT sensor_id, COUNT(*) AS count FROM my_table GROUP BY sensor_id
) t
GROUP BY count
ORDER BY count DESC
LIMIT    1, 18446744073709551615
于 2012-09-06T10:55:26.763 回答
1
SELECT sensor_id,COUNT(*) AS count
FROM table
GROUP BY sensor_id
ORDER BY count

将显示 sensor_id 列表以及它拥有的所有记录的计数,然后您可以手动检查是否有任何变化。

SELECT * FROM (
SELECT sensor_id,COUNT(*) AS count
FROM table
GROUP BY sensor_id
) AS t1
GROUP BY count 

将显示所有变化的计数,但 group by 将丢失有关哪些 sensor_id 具有哪些计数的信息。

- -编辑 - -

从我和 Eggyal 的答案中获取了一些信息并创建了这个,对于最常见的计数,我称之为 id 默认值,然后对于任何突出的值,我已经给它们单独的行。这样,如果您有许多结果Multi Row ,则可以保持表格的可读性,但如果所有计数都相同One Row,则也有一个简单的单行列。但是,如果您对编造的字符串感到满意,那么请选择 Eggyal 的答案。可能有点过头了,但这里有:

select 'default' as id,t5.c1 as count from(
select id,count(*) as c1 from your_table group by id having count(*)=
(select t4.count from
(
select max(t3.count2) as max,t3.count as count from 
(
select count(*) as count2,t2.count from
(
  SELECT id,COUNT(*) AS count
  FROM your_table
  GROUP BY id
) as t2 
  GROUP BY count
) as t3
) as t4)) as t5 group by count
union all
select t5.id as id,t5.c1 as count from(
select id,count(*) as c1 from your_table group by id having count(*)<>
(select t4.count from
(
select max(t3.count2) as max,t3.count as count from 
(
select count(*) as count2,t2.count from
(
  SELECT id,COUNT(*) AS count
  FROM your_table
  GROUP BY id
) as t2 
  GROUP BY count
) as t3
) as t4)) as t5
于 2012-09-06T10:51:30.630 回答