考虑 SQL Server 2008 数据库中的下表和数据:
CREATE TABLE sponsorships
(
sponsorshipID INT NOT NULL PRIMARY KEY IDENTITY,
sponsorshipLocationID INT NOT NULL,
sponsorshipArtworkID INT NOT NULL
);
INSERT INTO sponsorships (sponsorshipLocationID, sponsorshipArtworkID)
VALUES (1, 1);
INSERT INTO sponsorships (sponsorshipLocationID, sponsorshipArtworkID)
VALUES (1, 2);
INSERT INTO sponsorships (sponsorshipLocationID, sponsorshipArtworkID)
VALUES (2, 1);
INSERT INTO sponsorships (sponsorshipLocationID, sponsorshipArtworkID)
VALUES (2, 2);
INSERT INTO sponsorships (sponsorshipLocationID, sponsorshipArtworkID)
VALUES (3, 3);
INSERT INTO sponsorships (sponsorshipLocationID, sponsorshipArtworkID)
VALUES (4, 3);
INSERT INTO sponsorships (sponsorshipLocationID, sponsorshipArtworkID)
VALUES (5, 4);
INSERT INTO sponsorships (sponsorshipLocationID, sponsorshipArtworkID)
VALUES (6, 1);
INSERT INTO sponsorships (sponsorshipLocationID, sponsorshipArtworkID)
VALUES (7, 1);
INSERT INTO sponsorships (sponsorshipLocationID, sponsorshipArtworkID)
VALUES (7, 3);
SELECT *
FROM sponsorships s
ORDER BY s.sponsorshipLocationID, s.sponsorshipArtworkID
我怎样才能产生以下输出?
CREATE TABLE sponGroups
(
rank INT,
sponsorshipID INT,
sponsorshipLocationID INT,
sponsorshipArtworkID INT
);
INSERT INTO sponGroups VALUES (1, 1, 1, 1);
INSERT INTO sponGroups VALUES (1, 2, 1, 2);
INSERT INTO sponGroups VALUES (1, 3, 2, 1);
INSERT INTO sponGroups VALUES (1, 4, 2, 2);
INSERT INTO sponGroups VALUES (2, 5, 3, 3);
INSERT INTO sponGroups VALUES (2, 6, 4, 3);
INSERT INTO sponGroups VALUES (3, 7, 5, 4);
INSERT INTO sponGroups VALUES (4, 8, 6, 1);
INSERT INTO sponGroups VALUES (5, 9, 7, 1);
INSERT INTO sponGroups VALUES (5, 10, 7, 3);
SELECT *
FROM sponGroups sg
ORDER BY sg.rank, sg.sponsorshipID, sg.sponsorshipLocationID, sg.sponsorshipArtworkID
小提琴可用,在这里。
解释
艺术品展示在不同的地方。有些地方安装了双面艺术品(例如窗户),有些地方安装了单面艺术品(例如墙壁)。例如,位置 1 的艺术作品是双面的——它具有 SponsorshipArtworkID 1 和 2——而位置 5 的艺术作品是单面的(sponsorshipArtworkID 4)。
出于打印和安装目的,我需要一个查询来生成每件艺术品,无论是单面还是两面,以及与该作品相关的所有位置。(参考上面链接的小提琴中所需的输出。)例如,我需要告诉打印机:
- 打印双面艺术品(1,2)并将其安装在位置(1,2);
- 打印单面图稿 (3) 并将其安装在位置 (3,4);
- 打印单面图稿(4)并安装在位置(5);
- 打印单面图稿(1)并安装在位置(6);
- 打印双面图稿 (1,3) 并将其安装在位置 (7)。
请注意,有时会重复使用艺术作品,因此在单面和双面位置都使用了赞助艺术作品 ID 1。
我尝试使用 DENSE_RANK()、递归 CTE 和按组除法来解决此问题,但目前还无法解决。在此先感谢您的帮助。