条件选择使用多个if条件

时间:2013-02-09 01:59:13

标签: sql

我在表Players中有这样的行。

+-----------+----+----+----+----+----+----+----+----+
|  USERNAME | A  | B  | C  | D  | E  | F  | G  | H  |
+-----------+----+----+----+----+----+----+----+----+
|   Mike    | 45 | 34 | 56 | 58 | 29 | 74 | 39 | 48 |
+-----------+----+----+----+----+----+----+----+----+

现在我的查询应该是有点像......

SELECT USERNAME FROM PLAYERS 
IF 
 (DIFFERENCE BETWEEN A & B <20)

IF
 (DIFFERENCE BETWEEN C & D <20)

IF
 (DIFFERENCE BETWEEN E & F <20)
IF
 (DIFFERENCE BETWEEN G & H <20)

现在..如果四个条件中的任何两个都是真的,我必须选择用户名。 请帮忙

2 个答案:

答案 0 :(得分:1)

假设SQL Server

select
   username 
from(
    SELECT USERNAME,
        case when abs(a-b)<20 then 1 else 0 end A
        case when abs(c-d)<20 then 1 else 0 end b
        case when abs(e-f)<20 then 1 else 0 end c
        case when abs(g-h)<20 then 1 else 0 end d
    FROM PLAYERS
)tmp
WHERE tmp.a+tmp.b+tmp.c+tmp.d>=2

答案 1 :(得分:1)

假设mysql:

select username from (
    select username,
        if(b-a < 20, 1, 0) as ab,
        if(d-c < 20, 1, 0) as cd,
        if(f-e < 20, 1, 0) as ef,
        if(h-g < 20, 1, 0) as gh
    from players
) x where ab + cd + ef + gh = 2

如果a可能高于b,您可能需要使用abs()。如果两个或多个条件合适,您可能需要使用>= 2