我需要帮助解决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-输家第1组,......)。
所以我想知道赢家赢了多少次抢七局。 Tie break是Wx和Lx在7-6或6-7关系中出现的每一次。
我知道如何让所有行至少有一个平局,但由于一行(匹配)可以有很多平局,我在计算它时遇到问题。有什么想法吗?
由于
答案 0 :(得分: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)
也许您可以从联盟查询中查看视图,并在将来使用它来引用此表,因为我认为您最终会经常使用它。
答案 1 :(得分: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 |