0

我有 2 张桌子。

交易

id | customer_id | department_id
--------------------------------
1  |      1      |      2
--------------------------------
2  |      2      |      3
--------------------------------
3  |      2      |      4
--------------------------------
4  |      3      |      1
--------------------------------
5  |      2      |      3
--------------------------------

des_department

id |   caption 
-----------------
1  |  department1  
-----------------
2  |  department2
-----------------
3  |  department3
-----------------
4  |  department4
-----------------
5  |  department5
-----------------

我需要为每个customer_id显示部门标题。选择用户访问次数最多的部门。

输出示例:

    customer_id  |      caption
    ------------------------------
          1      |     department2
    ------------------------------
          2      |     department3
    ------------------------------
          3      |     department1
    ------------------------------

我也有自己的查询。但我显示所有访问次数。

我的查询:

    SELECT t.customer_id, t.terminal_i
  FROM transaction t WHERE (t.customer_id, t.terminal_id) IN
  ( SELECT t1.customer_id, t1.terminal_id
    FROM transaction t1 GROUP BY t1.customer_id
  )

我在 dbForge for Mysql 上工作。

4

2 回答 2

1

这种类型的查询在 MySQL 中是不必要的麻烦(因为 MySQL 既不支持公用表表达式也不支持窗口函数)。

一种方法是将表格聚合两次,一次是为了获得每个客户/部门的计数。第二次获得每个客户的最大值。然后将其加入到按客户和部门聚合的表中,以获得最大部门值。

SELECT t.customer_id, d.caption
FROM (SELECT td.customer_id, MAX(cnt) as maxcnt
      FROM (SELECT t.customer_id, t.deparment_id, COUNT(t.terminal_id) as cnt
            FROM transaction t 
            GROUP BY t.customer_id, t.department_id
           ) td
      GROUP BY t.customer_id
     ) tt JOIN
     (SELECT t.customer_id, t.deparment_id, COUNT(t.terminal_id) as cnt
      FROM transaction t 
      GROUP BY t.customer_id, t.deparment_id
     ) td
     ON t.customer_id = tt.customer_id and td.cnt = tt.cnt JOIN
     des_department d
     ON td.department_id = d.id
于 2015-05-14T10:53:13.850 回答
0

我通过在互联网上研究来写这个查询,可能对某人有帮助。这是sql代码:

SELECT customer_id, dd.caption 
  FROM 
  (SELECT t.customer_id, t.deparment_id
  FROM (SELECT t.customer_id, t.deparment_id, COUNT(t.deparment_id) AS ter
        FROM transaction t
        GROUP BY t.customer_id, t.deparment_id) t
  WHERE NOT EXISTS (SELECT 1
                    FROM (SELECT t.customer_id, t.deparment_id, COUNT(t.deparment_id) AS ter
                          FROM transaction t
                          GROUP BY t.customer_id, t.deparment_id) td
                          WHERE td.customer_id = t.customer_id AND td.ter>t.ter
                          ))
  tx
  INNER JOIN des_department dd
  ON tx.deparment_id = dd.id
于 2015-05-15T04:31:47.830 回答