2017-04-23 60 views
-2

我有一個sql查詢; 這個例子切爾西隊贏,輸,畫比賽結果 但我想在一個行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

我如何得出每個團隊的排風格

有人能幫助我嗎? Thanx

+1

什麼是期望的輸出?我猜你想要動態地調整數據......這在應用程序代碼中更好。 – GurV

+0

您正在使用哪些DBMS? –

+0

切爾西L,W,W,L,W ....這個慾望輸出 –

回答

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 
+0

接收到錯誤 ' Msg 156,Level 15,State 1,Line 3 關鍵字'Select'附近的語法錯誤。 Msg 102,Level 15,State 1,Line 14 ')'附近語法不正確。 ' 我嘗試改進,並做了一些更改,但它沒有奏效... –

+0

我錯過了一個關鍵詞。 「AS」就在開始的時候!上面添加。 –

+0

另外,我不應該在第一部分有'ORDER BY'。現在上面已刪除。我只測試了下半場,因爲我沒有「Matches」表的數據。 –