2014-12-03 63 views
1
SELECT 
    tbl_team.te_name, 
    tbl_player.pl_name, 
    tbl_scorer.sc_time 
FROM    
    tbl_scorer 
    INNER JOIN tbl_team on tbl_scorer.sID_team = tbl_team.pID_team 
    INNER JOIN tbl_player on tbl_scorer.sID_player = tbl_player.pID_player 
    INNER JOIN tbl_games on tbl_scorer.sID_game = tbl_games.pID_game 
WHERE tbl_games.pID_game = 9 

這給了我這樣的事情爲了在一列的出現次數和查詢附加列

+-------+----------+---+ 
    | TeamA | PlayerAA | 4 | 
    +-------+----------+---+ 
    | TeamB | PlayerBA | 4 | 
    +-------+----------+---+ 
    | TeamB | PlayerBB | 2 | 
    +-------+----------+---+ 
    | TeamA | PlayerAA | 1 | 
    +-------+----------+---+ 
    | TeamB | PlayerBB | 1 | 
    +-------+----------+---+ 

我想要的是像這樣的球隊列appaerances數量訂購此結果

+-------+----------+---+ 
| TeamB | PlayerBA | 4 | 
+-------+----------+---+ 
| TeamB | PlayerBB | 2 | 
+-------+----------+---+ 
| TeamB | PlayerBB | 1 | 
+-------+----------+---+ 
| TeamA | PlayerAA | 4 | 
+-------+----------+---+ 
| TeamA | PlayerAA | 1 | 
+-------+----------+---+ 

我能夠查詢被球隊名稱分組的行數與

SELECT 
     tbl_team.te_name, 
     count(tbl_team.te_name) 
    FROM    
     tbl_scorer 
     INNER JOIN tbl_team on tbl_scorer.sID_team = tbl_team.pID_team 
     INNER JOIN tbl_player on tbl_scorer.sID_player = tbl_player.pID_player 
     INNER JOIN tbl_games on tbl_scorer.sID_game = tbl_games.pID_game 
    WHERE tbl_games.pID_game = 9 group by tbl_team.te_name 

,但如何將它們結合起來,以獲得正確的順序?

回答

0

您可以使用此:

;WITH CTE AS (
SELECT 
    tbl_team.te_name, 
    tbl_player.pl_name, 
    tbl_scorer.sc_time 
FROM    
    tbl_scorer 
    INNER JOIN tbl_team on tbl_scorer.sID_team = tbl_team.pID_team 
    INNER JOIN tbl_player on tbl_scorer.sID_player = tbl_player.pID_player 
    INNER JOIN tbl_games on tbl_scorer.sID_game = tbl_games.pID_game 
WHERE tbl_games.pID_game = 9) 


SELECT a.* 
FROM CTE a 
CROSS APPLY (SELECT COUNT(te_name) as Count_te FROM CTE b WHERE a.te_name = b.te_name) x 
ORDER BY x.Count_te DESC, a.te_name, a.sc_time DESC 
0

對於特別給定的數據\

select dh.* from 
(SELECT 
tbl_team.te_name, 
tbl_player.pl_name, 
tbl_scorer.sc_time 
FROM    
tbl_scorer 
INNER JOIN tbl_team on tbl_scorer.sID_team = tbl_team.pID_team 
INNER JOIN tbl_player on tbl_scorer.sID_player = tbl_player.pID_player 
INNER JOIN tbl_games on tbl_scorer.sID_game = tbl_games.pID_game 
WHERE tbl_games.pID_game = 9) dh,  
(
SELECT 
tbl_team.te_name, 
count(tbl_team.te_name) rep 
FROM    
tbl_scorer 
INNER JOIN tbl_team on tbl_scorer.sID_team = tbl_team.pID_team 
INNER JOIN tbl_player on tbl_scorer.sID_player = tbl_player.pID_player 
INNER JOIN tbl_games on tbl_scorer.sID_game = tbl_games.pID_game 
WHERE tbl_games.pID_game = 9 
) xad 
where dh.te_name=xad.te_name 
order by xad.rep desc,dh.sc_time desc; 
+0

這會爲這一個給定的條目只是由alphabeth不要命的第一列由行的量查詢 – Markus 2014-12-03 09:10:29

+0

好@Markus我沒看到,結果應根據時代沒有出現......現在你可以檢查結果...我編輯我的答案 – 2014-12-03 09:37:06

相關問題