2

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

舞者(舞者姓名、性别、年龄)

舞蹈(舞者姓名、dvd_id、歌曲标题)

Dvd(dvd_id, song_title,成本)

歌曲(舞者姓名,歌曲标题,流派)

启动(舞者名称,dvd_id,年份)

我想选择其歌曲一起出现在一个或多个 dvd 中的舞者对,并且每对只打印一次。

这是我能得到的最接近的结果,它两次打印出同一对,但它们的名称在不同的列中:

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
4

2 回答 2

3

如果您将测试从 更改DANCER1.dancer_name <> DANCER2.dancer_nameDANCER1.dancer_name < DANCER2.dancer_name,您应该得到您想要的结果。

但是,由于您在 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
于 2013-02-14T08:24:05.810 回答
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

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

于 2016-08-22T07:59:07.047 回答