2013-05-28 130 views
1

如何計算5至6列中的另一個表中使用的一個表的主鍵?如何計算另一個表中的一個表的主鍵?

如果table1具有在table2應用於柱d1d2d3d4主鍵srno

我想統計table2中使用srno=1,2,3,4 ...等等的次數。

有誰知道該怎麼做?

+0

你說的 「表」 這裏是什麼意思?這是一個SQL問題嗎? – Bergi

+0

您的問題完全基於SQL,因此請提供您正在使用的數據庫(mysql或...)。還應該是表1中所有記錄的計數,還是隻針對特定索引? –

+0

是的,它的SQL問題。 – user2338384

回答

1

下面的查詢將返回的次數列D1,D2,D3和D4在表2(更新)中使用的每個值:

SELECT table1.srno, SUM(cnt) FROM 
    table1, 
    (SELECT d1 AS srno, COUNT(d1) AS cnt FROM table2 GROUP BY d1 
    UNION ALL 
    SELECT d2 AS srno, COUNT(d2) AS cnt FROM table2 GROUP BY d2 
    UNION ALL 
    SELECT d3 AS srno, COUNT(d3) AS cnt FROM table2 GROUP BY d3 
    UNION ALL 
    SELECT d4 AS srno, COUNT(d4) AS cnt FROM table2 GROUP BY d4) AS cnt_tbl 
WHERE table1.srno = cnt_tbl.srno 
GROUP BY table1.srno 

嘗試撥弄here.

如果」只重新計算一個特定主鍵(例如1),然後嘗試

SELECT SUM(cnt) FROM 
    (SELECT COUNT(*) AS cnt FROM table2 WHERE d1 = 1 
    UNION ALL 
    SELECT COUNT(*) AS cnt FROM table2 WHERE d2 = 1 
    UNION ALL 
    SELECT COUNT(*) AS cnt FROM table2 WHERE d3 = 1 
    UNION ALL 
    SELECT COUNT(*) AS cnt FROM table2 WHERE d4 = 1) AS cnt_tbl 

小提琴here

或者沒有UNION一個更優雅的解決方案:

SELECT SUM(cnt) FROM 
    (SELECT ((d1=1) + (d2=1) + (d3=1) + (d4=1)) AS cnt 
    FROM table2 
    WHERE d1 = 1 OR d2= 1 OR d3 = 1 OR d4 = 1) AS cnt_tbl 

Fiddle

+2

我認爲你需要'UNION ALL',否則重複會被壓制。 –

+0

哦,是的,你是對的,謝謝 – Mifeet

+0

srno table1在多列中使用。以上代碼是針對特定記錄的,bt記錄可以是多個。 – user2338384

相關問題