与表中的其他条目相比,查找唯一行

时间:2015-04-14 08:20:10

标签: sql

我有以下表格:

+-ID-+-USER--+--VALUE--+
|1   |'userA'|'MOV-AAA'|
|2   |'userB'|'MOV-AAA'|
|3   |'userB'|'MOV-BBB'|
|4   |'userC'|'MOV-AAA'|
|5   |'userC'|'MOV-BBB'|
|6   |'userD'|'MOV-EEE'|
+----+-------+---------+

我想现在找到与2位用户相比所有唯一的VALUE。与userA和userB一样。在比较userA和userB时,我会期待MOV-BBB。

目前我有这个问题:

SELECT A.userName, A.value
FROM testTable A
WHERE EXISTS
       (SELECT B.userName, B.value
        FROM testTable B
        WHERE B.value < A.value)

并收到此结果:

userName    value
userB       MOV-BBB
userC       MOV-BBB
userD       MOV-EEE

谢谢

1 个答案:

答案 0 :(得分:0)

你的问题不是很清楚。

您是否希望为指定的一对用户获取唯一值?如果是这样,试试这个:

DECLARE @FirstUserName char(5),
        @SecondUserName char(5)

SELECT  @FirstUserName = 'userA',
        @SecondUserName = 'userB'

SELECT userName, cValue
FROM testTable A
WHERE (UserName = @FirstUserName OR UserName = @SecondUserName)
AND Value NOT IN (
  SELECT Value
  FROM testTable
  WHERE (UserName = @FirstUserName OR UserName = @SecondUserName)
  AND UserName <> A.UserName
);

您是否希望获得指定用户对的第一个用户的结果?如果是这样,这将解决问题:

DECLARE @FirstUserName char(5),
        @SecondUserName char(5)

SELECT  @FirstUserName = 'userA',
        @SecondUserName = 'userB'


SELECT userName, cValue
FROM testTable A
WHERE (UserName = @FirstUserName)
AND Value NOT IN (
  SELECT Value
  FROM testTable
  WHERE UserName = @SecondUserName
);

或许你想为任何用户获得独特的价值观?在这种情况下,试试这个:

SELECT userName, cValue
FROM testTable A
WHERE cValue NOT IN (
  SELECT cValue
  FROM testTable
  WHERE UserName <> A.UserName
);

Here, play around with it yourself. (sql fiddle)