2015-12-03 44 views
0

我是SQL新手,我想寫一個查詢來在表中添加多行。添加特定的多行(SQL)

例如:

表:

matchid|player1id|player2id|player1score|player2score 
101 |20  |10  |0   |100 
101 |20  |10  |0   |100 
101 |20  |10  |0   |100 
201 |20  |10  |645   |0 
201 |20  |10  |100   |700 
201 |20  |10  |0   |100 

需要的輸出:

matchid|player1id|player2id|player1score|player2score 
101 |20  |10  |0   |300 
201 |20  |10  |745   |800 

注:我必須這樣做,而不使用GROUP BY

+0

'SELECT \t matchid, \t player1id, \t player2id, \t player1score = SUM(player1score), \t player2score = SUM(player2score) FROM yourTable GROUP BY \t matchid,player1id,player2id' –

+4

爲什麼你不想使用'GROUP BY'? –

+0

,因爲它的運營成本很高 – Khubaib

回答

1

在不使用GROUP BY

SELECT * 
FROM (
    SELECT DISTINCT matchid, player1id, player2id FROM tbl 
) AS t 
CROSS APPLY(
    SELECT 
     SUM(player1score), SUM(player2score) 
    FROM tbl 
    WHERE 
     matchid = t.matchid 
     AND player1id = t.player1id 
     AND player2id = t.player2id 
) AS x(player1score, player2score) 
+0

非常感謝@Felix。有效 :) – Khubaib

1
SELECT 
    matchid, player1is, player2id, 
    SUM(player1score) as player1score, 
    SUM(player2score) as player2score 
FROM 
    tablename 
GROUP BY 
    matchid, player1id, player2id 
+0

@downvoter,爲什麼投下票? –

+0

感謝迴應kaushik。對不起,我忘了提及我不想使用group by子句。 – Khubaib

+1

@wlcm好友..... –

1
select matchid,player1id,player2id,SUM(player1score) as 
player1score,SUM(player2score) as player2score 
FROM table1 
Group by player1id,player2id, matchid 
+0

感謝您的回覆tshoemake。對不起,我忘了提及我不想使用group by子句。 – Khubaib

0

這是否滿足要求?:

select 
    matchid, player1id, player2id, 
    (select sum(player1score from Table t2 where t2.matchid = t.matchid) as player1score, 
    (select sum(player2score from Table t2 where t2.matchid = t.matchid) as player2score 
from 
    (select distinct matchid, player1id, player2id from Table) t