SQL:如何比较不同行中的数据,只选择唯一的“对”,假设只有两个列?

时间:2013-02-14 08:02:18

标签: sql select group-by selection

我有几个表(粗体表示主键):

  

舞者( dancer_name,性别,年龄)

     

跳舞( dancer_name,dvd_id, song_title)

     

Dvd( dvd_id, song_title,费用)

     

歌曲( dancer_name,song_title,类型)

     

启动( dancer_name,dvd_id,年)

我想选择那些歌曲一起出现在一个或多个dvds中的舞者,每对只打印一次。

这是我可以得到的尽可能接近它打印出相同的两次,但他们的名字在不同的列中:

select distinct DANCER1.dancer_name, DANCER2.dancer_name, count(*) as count
  from Dancer DANCER1, Dancer DANCER2, Dance DANCE1, Dance DANCE2
 where DANCER1.dancer_name = DANCE1.dancer_name 
   and DANCER2.dancer_name = DANCE2.dancer_name 
   and DANCER1.dancer_name <> DANCER2.dancer_name
   and DANCE1.dvd_id = DANCE2.dvd_id
 group by DANCER1.dancer_name, DANCER2.dancer_name;

所以不要

Tom Jon
Jon Tom
Bob Sam
Sam Bob

我只想要

Tom Jon
Bob Sam

2 个答案:

答案 0 :(得分:3)

如果您将测试从DANCER1.dancer_name <> DANCER2.dancer_name更改为DANCER1.dancer_name < DANCER2.dancer_name,则应获得所需的结果。

Hovever,因为你在Dance表中使用名称作为键,所以你不需要加入Dancer表,查询可以简化为:

SELECT DANCE1.dancer_name, DANCE2.dancer_name, count(*) as count
FROM Dance DANCE1
INNER JOIN Dance DANCE2
ON DANCE1.dvd_id = DANCE2.dvd_id
WHERE DANCE1.dancer_name < DANCE2.dancer_name
GROUP by DANCE1.dancer_name, DANCE2.dancer_name

答案 1 :(得分:0)

declare @tmpTable table
(
    ID BIGINT IDENTITY(1,1),
    User1 BIGINT,
    User2 BIGINT
)

declare @tmpParticipants table
(
    Participant1 BIGINT,
    Participant2 BIGINT
)

insert into @tmpTable
Select distinct SendByID, SendToID
from InternalMessaging

declare @cnt bigint, @i bigint = 1, @user1 bigint, @user2 bigint

select @cnt = count(*) from @tmpTable

While(@i <= @cnt)
begin
        select @user1 = User1, @user2 = User2 from @tmpTable where ID = @i

        if not exists(select 1 from @tmpParticipants where Participant1 = @user1 and Participant2 = @user2)
        if not exists(select 1 from @tmpParticipants where Participant1 = @user2 and Participant2 = @user1)
        begin
                insert into @tmpParticipants
                select @user1, @user2
        end

        set @i = @i + 1
end

select * from @tmpParticipants

它对我有用。我希望,这将有助于解决您的问题。