如何从单个表中选择多个列值相同的行

时间:2011-12-28 22:02:22

标签: select sql-server-2008-r2

我有一个SQL Server表。现在,此表包含主键IdA, B, C, D, E, F, G

等列

现在我想从这个表中选择行

A=A, B=B, C=C, D=D and G > 132

所以我试图从这个表中选择哪些行A,B,C,D列具有相同的数据和G列数据> 132。

那我怎么能这样做?谢谢。

我尝试了此查询,但返回了相同的Id行

    SELECT TableA.Id,TableA.UserId,TableA.MaximumHp,TableA.Attack,TableA.Defense,TableA.SpAttack,TableA.SpDefense,TableA.Speed
FROM myTable as TableA
Inner Join myTable as TableB on 
TableA.MaximumHp = TableB.MaximumHp
  AND TableA.Attack = TableB.Attack
  AND TableA.Defense = TableB.Defense
    AND TableA.SpAttack = TableB.SpAttack
      AND TableA.SpDefense = TableB.SpDefense
        AND TableA.Speed = TableB.Speed
       AND TableA.Id != TableB.Id

SQL Server 2008 R2

2 个答案:

答案 0 :(得分:4)

听起来你想把桌子加到自己身上

SELECT *
FROM Table t1
Inner Join Table t2 on t1.A = t2.A
  AND t1.B = t2.B
  AND t1.C = t2.C
  AND t1.D = t2.D
  AND t1.G > 132
  AND t1.ID <> t2.ID

答案 1 :(得分:2)

我认为你的意思是重复的。告诉我这是否是您正在寻找的。

SELECT [Table].A, [Table].B, [Table].C, [Table].D, [Table].E, [Table].F, [Table].G
FROM [Table] LEFT JOIN (SELECT A, B, C, D FROM [Table] 
GROUP BY A, B, C, D
HAVING count(*) > 1)
AS sub ON ([Table].A=sub.A) AND ([Table].B=sub.B) AND ([Table].C=sub.C) AND ([Table].D=sub.D)
WHERE G>132 and sub.A is not null;

这将为您提供a,b,c和D等于表中另一行的所有行...并且G&gt; 132