2016-01-14 75 views
0

我需要幫助解決我在mysql中遇到的問題。如何計算mysql中兩個依賴列的發生次數

所以我有一個結構類似這樣的網球成績表:

W1 | L1 | W2 | L2 | W3 | L3 | W4 | L4 | W5 | L5 
------------------------------------------------ 
6 7 6 1 7 6 
6 1 6 1 
5 7 6 7 
6 1 7 5 6 7 6 7 7  5 

有可以播放最大爲5套,和(每一套保存在自己的列W1-贏家第1套,L1 - 輸家第一盤......)。

所以我想知道有多少個決勝者贏得和輸了。 聯繫休息是Wx和Lx在7-6或6-7關係的每一次發生。

我知道如何獲得至少有一個平局休息的所有的行,但作爲一個行(匹配)可以有很多平局,我有計算它的問題。有任何想法嗎?

感謝

+1

「所以我有結構化這樣的網球成績表:」 是的。修復。見正常化。 – Strawberry

+0

你有關於網球成績結構的建議嗎? –

+0

數據存儲與數據檢索和顯示混淆。一個典型的結構可能是:'match_id,set_no,player1_score,player2_score' – Strawberry

回答

1

首先,你的表架構是不是最大的。一個更好的模式是:

Match | Set | W | L 
--------------------- 
    1  1  6 7 
    1  2  6 3 
    1  3  5 7 
    1  4  3 6 
    2  1  6 7 
    2  2  6 7 
    2  3  6 2 
    2  4  3 6 

然後將查詢將是:

SELECT count(*) FROM <table> WHERE (W=6 AND L=7) OR (W=7 AND L=6) 

因此,我們可以讓你的表格看起來像一個通過SQL上方,然後使用SQL作爲作弊上面的SQL中的一個子查詢。爲了讓你看起來像雷:

SELECT 1 as set, W1 as W, L1 as L FROM <table> 
UNION ALL 
SELECT 2, W2 as W, L2 as L FROM <table> 
UNION ALL 
SELECT 3, W3 as W, L3 as L FROM <table> 
UNION ALL 
SELECT 4, W4 as W, L4 as L FROM <table> 
UNION ALL 
SELECT 5, W5 as W, L5 as L FROM <table> 

結合他們:

SELECT count(*) 
FROM (
    SELECT 1 as set, W1 as W, L1 as L FROM <table> 
    UNION ALL 
    SELECT 2, W2 as W, L2 as L FROM <table> 
    UNION ALL 
    SELECT 3, W3 as W, L3 as L FROM <table> 
    UNION ALL 
    SELECT 4, W4 as W, L4 as L FROM <table> 
    UNION ALL 
    SELECT 5, W5 as W, L5 as L FROM <table> 
) as unionSub 
WHERE (W=6 AND L=7) OR (W=7 AND L=6) 

也許你可以做一個觀點指出,聯合查詢的,因爲我會用它在未來引用此表想象你最終會經常使用它。

+0

非常好,謝謝,這符合我的需求... –

1

當你有lemmons做lemmonade。這不是preaty,但也許幫助你到達那裏。

SQL Fiddle Demo

SELECT 
     CASE WHEN `W1` = 7 and `L1` = 6 THEN 1 ELSE 0 END + 
     CASE WHEN `W2` = 7 and `L2` = 6 THEN 1 ELSE 0 END + 
     CASE WHEN `W3` = 7 and `L3` = 6 THEN 1 ELSE 0 END + 
     CASE WHEN `W4` = 7 and `L4` = 6 THEN 1 ELSE 0 END + 
     CASE WHEN `W5` = 7 and `L5` = 6 THEN 1 ELSE 0 END as Winner_break_won, 
     CASE WHEN `W1` = 6 and `L1` = 7 THEN 1 ELSE 0 END + 
     CASE WHEN `W2` = 6 and `L2` = 7 THEN 1 ELSE 0 END + 
     CASE WHEN `W3` = 6 and `L3` = 7 THEN 1 ELSE 0 END + 
     CASE WHEN `W4` = 6 and `L4` = 7 THEN 1 ELSE 0 END + 
     CASE WHEN `W5` = 6 and `L5` = 7 THEN 1 ELSE 0 END as Winner_break_lost 
FROM tennis  

輸出

| Winner_break_won | Winner_break_lost | 
|------------------|-------------------| 
|    1 |     1 | 
|    0 |     0 | 
|    0 |     1 | 
|    0 |     2 | 
+0

謝謝,這也是有用的解決方案! –