2016-05-12 48 views
-2

我有一個包含2列X,Y的表格。我想計算兩列中每條記錄的出現次數。 如:Mysql:獲取兩列中所有值的計數

X | Y 

A | A 
B | A 
B | C 
D | C 

結果應該是

variable | X_count | Y_count 
A  | 1  | 2 
B  | 2  | 0 
C  | 0  | 2 
D  | 1  | 0 

如何在mysql中實現這一目標?

編輯:好吧,花了幾個小時後,我確保Y中的所有值都是X的子集,即對於任何變量,X_count永遠不會爲0。這有助於優化嗎?

回答

0

我想你需要通過

select v.variable, a.count(*), b.count(*) 
    from 
    (select x as variable 
    from my_table 
    union select y 
    from my_table) as v 
    inner join my_table as a on a.X = v.variable 
    inner join my_table as b on b.y = v.variable 
    group by v.variable 

事實上在Y工會臨時表和組是X的一個子集,允許以避免工會,然後但無論如何,我們需要不同的X

select v.variable, a.count(*), b.count(*) 
    from 
    (select distinct x as variable 
    from my_table) as v 
    inner join my_table as a on a.X = v.variable 
    inner join my_table as b on b.y = v.variable 
    group by v.variable 
+0

我想你錯過了工會後選擇的錯字。 IMO也不需要顯着。有什麼方法可以優化查詢,2個內部連接在桌面上佔用大量時間。 – codeKNIGHT

+0

我檢查了錯字,並更新了答案..對於optmize ..你可以認爲在index .. key(x,y).. – scaisEdge

+0

你有多少行..? – scaisEdge

0
select variable,count(x),count(y) from 
(select distinct x as variable,x,y from my_table 
union all 
select distinct y as variable, x,y from my_table)v 
group by variable order by variable; 
+0

這兩個計數是相同的 – codeKNIGHT

+0

是的,工作! – Priyanshu