2015-05-14 34 views
0

我有2個表。我如何在sql中計數相同的行

交易

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工作爲MySQL。

+0

[SQL選擇僅在一個色譜柱的最大值的行(可能重複http://stackoverflow.com/questions/7745609/sql-select-only-rows-with- max-value-on-a-column) – sevenforce

+0

@sevenforce您的鏈接是關於只顯示最大行數的。在我的例子中,我需要爲每個用戶計算他訪問過的部門,並顯示哪個部門用戶訪問的比其他部門多。 –

回答

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 
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 
+0

對不起,我困惑你。 terminal_id和這個department_id是一樣的,我只用其他詞來解釋。我也糾正了我的例子,你的答案能否正確答案。 –

相關問題