我有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上工作。
答案 0 :(得分: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
答案 1 :(得分: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