我在表格中有以下数据
**TEAM NAME**
Germany
Holland
Scotland
Brazil
我期待下面的数据与订单相同,请帮忙
**ScheduledMatches**
Germany VS Holland
Germany VS Scoltland
Germany VS Brazil
Holland VS Scoltland
Holland VS Brazil
Scoltland VS Brazil
由于 Vijay Sagar
答案 0 :(得分:2)
您可以先为每个团队计算ROW_NUMBER
,然后根据计算出的<
使用rn
进行自我加入:
CREATE TABLE #teams(name VARCHAR(100));
INSERT INTO #teams(name)
VALUES('Germany'), ('Holland'), ('Scotland'), ('Brazil');
;WITH cte AS
(
SELECT *, rn = ROW_NUMBER() OVER (ORDER BY (SELECT 1))
FROM #teams
)
SELECT CONCAT(c1.name, ' vs ', c2.name) AS result
FROM cte c1
JOIN cte c2
ON c1.rn < c2.rn
-- ORDER BY result;
的 LiveDemo
强>
CONCAT
可从SQL Server 2012+
获得,如果您使用较低版本+
来连接字符串。
答案 1 :(得分:1)
DECLARE @t TABLE (Team VARCHAR(100))
INSERT INTO @t (Team)
VALUES
('Germany'),
('Holland'),
('Scotland'),
('Brazil')
;WITH cte AS
(
SELECT *, RowNum = ROW_NUMBER() OVER (ORDER BY 1/0)
FROM @t
)
SELECT t2.Team + ' vs ' + t1.Team
FROM cte t1
JOIN cte t2 ON t1.RowNum > t2.RowNum
输出 -
---------------------------
Germany vs Holland
Germany vs Scotland
Germany vs Brazil
Holland vs Scotland
Holland vs Brazil
Scotland vs Brazil
答案 2 :(得分:0)
下面的代码可以帮助你!!!
SELECT
a.M +' VS '+ b.M AS [**ScheduledMatches**]
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 order by 1/0) AS no
FROM (
VALUES ('Germany'), ('Holland'), ('Scotland'), ('Brazil')
) t (m)
) a
JOIN (
SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 order by 1/0) AS no
FROM (
VALUES ('Germany'), ('Holland'), ('Scotland'), ('Brazil')
) t (m)
) b ON a.no < b.no
输出:
**ScheduledMatches**
Germany VS Holland
Germany VS Scotland
Germany VS Brazil
Holland VS Scotland
Holland VS Brazil
Scotland VS Brazil