您可以使用ROW_NUMBER
和“三角连接”:
WITH cte AS
(
SELECT *, rn = ROW_NUMBER() OVER(PARTITION BY date ORDER BY Name)
FROM tab
)
SELECT c.Name, c2.Name
FROM cte c
JOIN cte c2
ON c.Date = c2.Date
AND c.rn < c2.rn;
LiveDemo
输出:
╔═══════╦═══════╗
║ Name ║ Name ║
╠═══════╬═══════╣
║ John ║ Mark ║
║ John ║ Mia ║
║ John ║ Peter ║
║ Mark ║ Mia ║
║ Mark ║ Peter ║
║ Mia ║ Peter ║ -- ORDER BY based on `Name`
║ Billy ║ John ║ -- same here `B` before `J`
╚═══════╩═══════╝
笔记:
要获得稳定的排序,您需要添加将指示组内顺序的列具有相同的date
. 我使用过Name
,但它交换了最后两行中的名称。
带ID
列的版本:
CREATE TABLE tab(ID INT IDENTITY(1,1)
,Date DATE NOT NULL
,Name VARCHAR(6) NOT NULL);
INSERT INTO tab(Date,Name)
VALUES ('1/1/2010','John'), ('1/1/2010','Mark'), ('1/1/2010','Peter')
,('1/1/2010','Mia'), ('2/4/2010','John'),('2/4/2010','Billy');
WITH cte AS
(
SELECT *, rn = ROW_NUMBER() OVER(PARTITION BY date ORDER BY ID)
FROM tab
)
SELECT c.Name, c2.Name
FROM cte c
JOIN cte c2
ON c.Date = c2.Date
AND c.rn < c2.rn;
LiveDemo 2
输出:
╔═══════╦═══════╗
║ Name ║ Name ║
╠═══════╬═══════╣
║ John ║ Mark ║
║ John ║ Peter ║
║ John ║ Mia ║
║ Mark ║ Peter ║
║ Mark ║ Mia ║
║ Peter ║ Mia ║
║ John ║ Billy ║
╚═══════╩═══════╝