SQL查询根据计数和一些过滤器查找MAX值

时间:2018-04-12 19:20:59

标签: mysql sql group-by count

表如下所示:

/* Create a table called test */
CREATE TABLE test(Id integer PRIMARY KEY,Col_Key text, Ng text, node text);

/* Create few records in this table */
INSERT INTO test VALUES(1,'key1','g1','n2');
INSERT INTO test VALUES(2,'key1','g2','n3');
INSERT INTO test VALUES(3,'key2','g3','n1');
INSERT INTO test VALUES(4,'key2','g4','n1');
INSERT INTO test VALUES(5,'key3','g5','n1');
INSERT INTO test VALUES(6,'key3','g6','n2');
INSERT INTO test VALUES(7,'key4','g7','n1');
INSERT INTO test VALUES(8,'key4','g8','n1');
INSERT INTO test VALUES(9,'key5','g8','n4');
INSERT INTO test VALUES(10,'key5','g9','n4');
INSERT INTO test VALUES(11,'key6','g10','n4');
INSERT INTO test VALUES(12,'key6','g11','n4');
INSERT INTO test VALUES(13,'key7','g11','n4');
INSERT INTO test VALUES(14,'key9','q11','n3');
INSERT INTO test VALUES(15,'key9','q11','n2');
INSERT INTO test VALUES(16,'key10','q12','n1');
COMMIT;

我正在尝试从节点列获取具有最大计数且其Ng值以g开头的值。

我做过这样的事情:

SELECT TEMP.node,COUNT(TEMP.node) FROM (SELECT Col_Key,Ng,node 
from test WHERE (Ng LIKE 'g%')) TEMP GROUP BY TEMP.node;

给出了以下结果:

enter image description here

但是,在结果中我只想要结果中的n4和n1(只有节点列不计数),因为它们具有最大计数。我无法在查询中添加此部分。请帮忙。

以上数据只是一小段数据,但我的SQL表中会有数千行,所以我的查询应该是有效的。

PS: - 我尝试过以下方式:

SELECT TEMP2.node,TEMP2.CNT FROM (SELECT TEMP.node,COUNT(TEMP.node) AS CNT FROM (SELECT Col_Key,Ng,node 
from test WHERE (Ng LIKE 'g%')) TEMP GROUP BY TEMP.node) TEMP2 WHERE TEMP2.CNT = (SELECT MAX(TEMP2.CNT) FROM TEMP2);

但是where子句的查询的最后一部分是错误的,因为它无法找到表TEMP2。

但是这里有各种各样的想法让我知道我想要什么。

结果应该是:

node 
n1
n4

3 个答案:

答案 0 :(得分:1)

如下:

SELECT
  t.node,
  COUNT(*)
FROM
  test t
WHERE
  t.Ng like 'g%'
GROUP BY
  t.node
HAVING
  COUNT(*) = (
    SELECT 
      MAX(a.count_of_nodes)
    FROM
    (
      SELECT
        node,
        COUNT(*) AS count_of_nodes
      FROM
        test
      WHERE
        Ng like 'g%'
      GROUP BY
        node
    ) a
  )
;
祝你好运!

答案 1 :(得分:0)

您可以使用temptable轻松处理这种情况,如下所示:

CREATE TEMPORARY TABLE temptable AS (
  SELECT TEMP.node,COUNT(TEMP.node) as cnt FROM (SELECT Col_Key,Ng,node 
  from test WHERE (Ng LIKE 'g%')) TEMP GROUP BY TEMP.node
)
select node, cnt
from temptable t
where cnt = (select max(cnt) from temptable)

请参阅:http://www.sqlfiddle.com/#!9/e749de/1/0

答案 2 :(得分:0)

您的查询不需要子查询:

select node, count(*) 
from test
where Ng LIKE 'g%'
group by node;

获得一个最大值很容易(使用limit),但你想要所有这些。一种方法使用子查询和having子句:

select node, count(*) 
from test
where Ng LIKE 'g%'
group by node
having count(*) = (select count(*)
                   from test t2
                   where t2.Ng LIKE 'g%'
                   group by t2.node
                   order by count(*) desc
                   limit 1
                  );

这比它需要的更复杂,因为MySQL(8.0之前版本)既不支持窗口功能也不支持CTE。令人高兴的是,MySQL 8 +中的语法更简单。