sql同名但值不同

时间:2012-10-25 11:19:52

标签: sql sql-server

如何检索具有相同名称的所有行,但它们具有不同的值?例如,我有这个表:

Name|Value|Description
Rob |Val1 |Text1
Alex|Val1 |Text2
Alan|Val2 |Text3
Alex|Val2 |Text4
Alex|Val2 |Text5  
Alan|Val2 |Text6

我希望查询只返回出现多次但具有不同值的人。结果将是:

Alex|Val1 |Text2 
Alex|Val2 |Text4 
Alex|Val2 |Text5

编辑:我在初始表中添加了另一行。一些问题也会将Alan作为结果的一部分归还。我不希望这样,因为它显然具有相同的价值。如何实现这一目标?

4 个答案:

答案 0 :(得分:4)

尝试将joinsybqueryhaving

一起使用
  select p.Name,p.Value,p.Description
    from persons P
    join ( select Name,Value
           from persons
            group by Name,Value
            having count(1)>1
          ) c on p.Name = c.Name
              and p.Value = c.Value
    order by p.Name;

subquery子句中的exists

select p.Name,p.Value,p.Description
from persons P
where exists
     ( select Name,Value
       from persons c
        where p.Name = c.Name
        group by Name,Value
        having count(1)>1
      ) 
order by p.Name          

SQL Fiddle演示

更新问题的解决方案

select * 
from Persons c
where name in 
(
select  Name   from(
       select Name,Value 
       from persons        
        group by Name,Value) T

group by Name
  having count(1)>1
)  

SQL Fiddle演示

答案 1 :(得分:2)

这是一个简单的工作解决方案:

SELECT t.Name, t.Value, t.Description
FROM t_table AS t
JOIN (
    SELECT Name
    FROM (
       SELECT Name FROM  t_table GROUP BY Name,Value
    ) AS sub1
    GROUP BY Name
    HAVING COUNT(*)>1
) AS sub2 ON (t.Name=sub2.Name)
ORDER BY t.Name, t.Value

答案 2 :(得分:2)

只为了好玩...... 交叉连接可能会起作用(我还没有测试过):

select distinct 
    p1.*
from 

    Persons p1 
cross join 
    Persons p2 
where 
        p1.Name = p2.Name 
    and p1.Value <> p2.value
    and p1.Description <> p2.Description 

现在你可以开始讨论它的效率...... (但我不会参与其中......)

答案 3 :(得分:0)

你可以做点什么

  

SELECT * FROM TABLE1 AS A WHERE 1 = CASE WHEN       (          SELECT COUNT(*)FROM TABLE1 AS B WHERE B.NAME = A.NAME       )&gt; 1那么1节0结束