在SQL Server中使用条件查找同一表上的值组合

时间:2015-04-27 08:30:39

标签: sql-server tsql

我有一个名为PlayerScore的表格,其中包含玩家名称及其平均分数:

Id  Name     Average
1   Sakib      80
2   Tamim      70
3   Mushfiq    60
4   Sabbir     50
5   Ashraful   20
6   Aftab      40
7   Rubel      30
8   Kalu       10

我想根据条件找到他们的合作伙伴关系, 平均分数大于40的palyer不能与得分低于40的球员合作。 我尝试了以下查询:

select a.Name,a.Average,b.Name,b.Average from ((select * from PlayerScore where Average<=40) as a inner join (select * from PlayerScore where Average<=40) as b on a.Id < b.Id) 

union 

select a.Name,a.Average,b.Name,b.Average from ((select * from PlayerScore where Average>=40) as a inner join (select * from PlayerScore where Average>=40) as b on a.Id < b.Id)

导致:

Name    Average Name    Average
Aftab    40     Kalu    10
Aftab    40     Rubel   30
Ashraful 20     Aftab   40
Ashraful 20     Kalu    10
Ashraful 20     Rubel   30
Mushfiq  60     Aftab   40
Mushfiq  60     Sabbir  50
Rubel    30     Kalu    10
Sabbir   50     Aftab   40
Sakib    80     Aftab   40
Sakib    80     Mushfiq 60
Sakib    80     Sabbir  50
Sakib    80     Tamim   70
Tamim    70     Aftab   40
Tamim    70     Mushfiq 60
Tamim    70     Sabbir  50

他们的任何解决方案都没有使用UNION

3 个答案:

答案 0 :(得分:2)

select distinct a.Name,a.Average,b.Name,b.Average 
from PlayerScore a 
join PlayerScore b 
  on a.Id < b.Id 
     and (    a.Average<=40 and b.Average<=40
           or a.Average>=40 and b.Average>=40
         )

它可能会产生相同的计划。

答案 1 :(得分:1)

也许你可以这样做:

SELECT
    t.*,
    t2.*
FROM
    PlayerScore AS t
    CROSS JOIN PlayerScore AS t2
WHERE t.Average>=40 AND t2.Average<40
ORDER BY t.Name

答案 2 :(得分:0)

您可以根据条件创建2个组,并为它们提供不同的值,然后根据该值进行连接。这样的事情。

;WITH PlayerScore as
(
SELECT 1 AS Id,'Sakib' AS Name,80 AS Average
UNION ALL SELECT 2,'Tamim',70
UNION ALL SELECT 3,'Mushfiq',60
UNION ALL SELECT 4,'Sabbir',50
UNION ALL SELECT 5,'Ashraful',20
UNION ALL SELECT 6,'Aftab',40
UNION ALL SELECT 7,'Rubel',30
UNION ALL SELECT 8,'Kalu',10
),PlayerCriteria AS
(
SELECT *,CASE WHEN Average >= 40 THEN 1 ELSE 0 END joincondition
FROM PlayerScore
)

SELECT * FROM PlayerCriteria C1
INNER JOIN PlayerCriteria C2 ON C1.joincondition = C2.joincondition
AND C1.Id > C2.Id