简体   繁体   English

计算2个字段中不同值的出现次数

[英]Count occurrences of distinct values in 2 fields

I am trying to find a MySQL query that will find distinct values in a particular field, count the number of occurrences of that value in 2 fields (1_user, 2_user) and then order the results by the count. 我试图找到一个MySQL查询,它将在特定字段中找到不同的值,计算2个字段(1_user,2_user)中该值的出现次数,然后按计数对结果进行排序。

example db 示例db

+------+-----------+-----------+
|   id | 1_user    | 2_user    |
+------+-----------+-----------+
|    1 |       2   | 1         | 
|    2 |       3   | 2         | 
|    3 |       8   | 7         | 
|    4 |       1   | 8         | 
|    5 |       2   | 8         |
|    6 |       3   | 8         |  
+------+-----------+-----------+

expected result 预期结果

user       count
-----      -----
8          4
2          3
3          2
1          2

The Query 查询

SELECT user, count(*) AS count
FROM
(
    SELECT 1_user AS USER FROM test

    UNION ALL

    SELECT 2_user FROM test
) AS all_users
GROUP BY user
ORDER BY count DESC

Explanation 说明

List all the users in the first column. 列出第一列中的所有用户。

SELECT 1_user AS USER FROM test

Combine them with the users from the second column. 将它们与第二列中的用户组合。

UNION ALL
SELECT 2_user FROM test

The trick here is the UNION ALL which preserves duplicate values. 这里的技巧是UNION ALL保留重复值。

The rest is easy -- select the results you want from the subquery: 其余很简单 - 从子查询中选择所需的结果:

SELECT user, count(*) AS count

aggregate by user: 用户聚合:

GROUP BY user

and prescribe the order: 并订明订单:

ORDER BY count DESC
SELECT u, count(u) AS cnt 
FROM (
    SELECT 1_user AS u FROM table
    UNION ALL
    SELECT 2_user AS u FROM table
) subquery 
GROUP BY u
ORDER by cnt DESC

Take the 2 queries: 拿2个查询:

SELECT COUNT(*) FROM table GROUP BY 1_user

SELECT COUNT(*) FROM table GROUP BY 2_user

Now combine them: 现在结合它们:

SELECT user, SUM(count) FROM
  ((SELECT 1_user as user FROM table)
  UNION ALL
  (SELECT 2_user as user FROM table))
GROUP BY user, ORDER BY count DESC;

I think this what you are looking for since your expected result did not include 7 我认为这是你正在寻找的,因为你的预期结果不包括7

select usr, count(usr) cnt from
(
   select user_1 usr from users
   union all
   select user_2 usr from users
) u
where u.usr in (select user_1 from users)
group by usr
order by count(u.usr) desc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM