添加特定的多行(SQL)

时间:2015-12-03 05:24:50

标签: sql sql-server

我是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

的情况下执行此操作

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

答案 2 :(得分: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) 

答案 3 :(得分: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