我有一个SQL查询; 这个例子切尔西队获胜,失败,平局比赛结果 但我希望行中的查询结果(对于每个团队)
例如:
切尔西W,W,L,D,W阿森纳W,D,D,L,L
ManCity D,W,L,D,W
Select
date, Team,
(case when fthg > ftag then 'W' when fthg = ftag then 'D' when ftag > fthg then 'L' end)
from
(
select div, hometeam team, date, fthg, ftag from Matches
union all
select div, awayteam team, date, ftag, fthg from Matches
) a
where Team like '%chelsea%'
order by date desc, team desc
date Team Mres
2016-08-15 00:00:00.000 Chelsea W
2016-08-27 00:00:00.000 Chelsea W
2016-09-16 00:00:00.000 Chelsea L
2016-10-15 00:00:00.000 Chelsea W
2016-10-23 00:00:00.000 Chelsea W
2016-11-05 00:00:00.000 Chelsea W
2016-11-26 00:00:00.000 Chelsea W
2016-12-11 00:00:00.000 Chelsea W
2016-12-26 00:00:00.000 Chelsea W
2016-12-31 00:00:00.000 Chelsea W
2017-01-22 00:00:00.000 Chelsea W
2017-02-04 00:00:00.000 Chelsea W
2017-02-25 00:00:00.000 Chelsea W
2017-04-01 00:00:00.000 Chelsea L
2017-04-05 00:00:00.000 Chelsea W
我如何导致每个团队的行样式
有人能帮助我吗?感谢名单
答案 0 :(得分:0)
这个怎么样?您将看到第一部分是基于您的代码的CTE(仅更改/添加了列别名并删除了顺序),这允许脚本的其余部分像表格一样引用它:
With TeamResults as
(
Select
date as MatchDate, Team,
(case when fthg > ftag then 'W' when fthg = ftag then 'D' when ftag > fthg then 'L' end) Mres
from
(
select div, hometeam team, date, fthg, ftag from Matches
union all
select div, awayteam team, date, ftag, fthg from Matches
) a
where Team like '%chelsea%'
)
SELECT t2.Team, TeamResultList = replace
((SELECT Mres AS [data()]
FROM TeamResults t1
WHERE t1.Team = t2.Team
ORDER BY t1.MatchDate FOR xml path('')), ' ', ',')
FROM TeamResults t2
GROUP BY t2.Team