通过在MySQL中对一列或另一列进行分组来记录计数

时间:2018-05-30 22:08:59

标签: mysql

我在mysql中有一张表格,如下所示。

+-----+---+---+----+
|tests|val|asd|cnty|
+-----+---+---+----+
|test2|  N|  2|  UK|
| null|  Y|  1|  UK|
|test1|  N|  2|null|
|test1|  N|  3|null|
|test3|  N|  4| AUS|
|test4|  Y|  5|null|
|test1|  Y|  1|null|
+-----+---+---+----+

我希望count testscnty具有相同值的值select tests, cnty, count(*) ask from db_name.table_name group by tests, cnty

我在下面做了

+-----+----+---+
|tests|cnty|ask|
+-----+----+---+
|test4|null|  1|
|test1|null|  3|
|test2|  UK|  1|
|test3| AUS|  1|
| null|  UK|  1|
+-----+----+---+

我得到的结果是

expected result

+-----+----+---+ |tests|cnty|ask| +-----+----+---+ |test4|null| 1| |test1|null| 3| |test2| UK| 2| |test3| AUS| 1| | null| UK| 2| +-----+----+---+ 位于

之下
new table

我怎样才能做到这一点?

  

修改

+-----+---+---+----+ |tests|val|asd|cnty| +-----+---+---+----+ |test2| N| 2| UK| | null| Y| 1| UK| |test1| N| 2|null| |test1| N| 3|null| |test3| N| 4| AUS| |test4| Y| 5|null| |test1| Y| 1|null| |test1| Y| 6| US| |test1| Y| 6| IND| +-----+---+---+----+

expected result

+-----+----+---+ |tests|cnty|ask| +-----+----+---+ |test3| AUS| 1| |test1| US| 5| |test2| UK| 2| |test4|null| 1| | null| UK| 2| |test1|null| 5| |test1| IND| 5| +-----+----+---+

expression.Find( What , After , LookIn , LookAt , SearchOrder , SearchDirection , MatchCase , MatchByte , SearchFormat )

1 个答案:

答案 0 :(得分:2)

看起来asktestscnty计数的最大值。所以一个查询获得一个计数,另一个查询获得另一个计数,然后将它们与主表连接并使用更高的一个。

SELECT DISTINCT t.tests, t.cnty, GREATEST(t1.count, t2.count) AS ask
FROM table_name AS t
JOIN (SELECT tests, COUNT(*) AS count
      FROM table_name
      GROUP BY tests) AS t1 ON t.tests <=> t1.tests
JOIN (SELECT cnty, COUNT(*) AS count
      FROM table_name
      GROUP BY cnty) AS t2 ON t.cnty <=> t2.cnty

DEMO

必须使用<=> null-safe相等运算符,以便正确连接表中的空值。