У меня есть таблица в 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
значения, в которых либо tests
либо cnty
имеют одинаковые значения.
Я сделал, как показано ниже
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|
+-----+----+---+
Похоже, что ask
- это максимум tests
или cnty
. Так что сделайте один запрос, который получает один счет, другой запрос, который получает другой счет, затем присоединяется к ним с главной таблицей и использует более высокий.
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
Необходимо использовать <=>
нулевой оператор равенства, чтобы нулевые значения в таблице были правильно соединены.
tests
имеет разныйcnty
?tests