SQL查询 - 前3的SUM和按值的GROUP

时间:2018-05-22 19:07:04

标签: mysql sql group-by

对于SQL来说,我很擅长查询。

我的数据库包含ID,WEIGHT,TEAM

我想返回每个ID前3个WEIGHTS的结果,将它们合并在一起并按TEAM分组。 ID的每个其他条目都将被忽略。所以结果将会读取TEAM WEIGHT。

SELECT id, team, SUM( weight ) AS total
FROM (

SELECT id, team, weight
FROM database m
WHERE (

SELECT COUNT( * ) 
FROM database mT
WHERE 
mT.id = m.id
AND mT.weight >= m.weight
) <=3
)tmp

GROUP BY team
ORDER BY total DESC

这是我的努力,但绝对不对。很抱歉,如果这是一个基本的查询,但我在网上研究没有喜悦。我会感激任何帮助,因为我有点卡住了。

Table

ID    Weight    Team
1     100       A
5     200       C *
1     300       A *
1     100       A
3     50        
1     200       A *
5     20        C
1     150       A *
5     200       C *
4     50        B *
5     200       C *
6     100       A *
2     50        C
6     100       A *
2     100       C *
6     100       A *
2     100       C *
6     50        A 
2     200       C *

预期结果将是:

Team   Total
C      1000
A      950
B      50

我已经加注了应该汇总的值(按团队分组的每个ID排名前3位)。值得注意的是,它并不是每支球队的前6名。它必须是每个ID加在一起的前3个,然后再次添加不同ID的前3个以使团队合计。

2 个答案:

答案 0 :(得分:0)

这是怎么回事?

select team, sum(weight) from (
    select id, team, weight, row_number() over(partition by id order by weight desc) rownum from (
    select id, team, sum(weight) weight
    from database
    group by id, team)a)b
    where rownum<=3
    group by team

答案 1 :(得分:0)

希望这可以解决问题。

CREATE TABLE TEST_DATA
  ( id VARCHAR(10),
    weight INTEGER,
    team VARCHAR(10)
  );

INSERT INTO TEST_DATA VALUES('5',200,'C');
INSERT INTO TEST_DATA VALUES('1',300,'A');
INSERT INTO TEST_DATA VALUES('1',100,'A');
INSERT INTO TEST_DATA VALUES('3',50,'');
INSERT INTO TEST_DATA VALUES('1',200,'A');
INSERT INTO TEST_DATA VALUES('5',20,'C');
INSERT INTO TEST_DATA VALUES('1',150,'A');
INSERT INTO TEST_DATA VALUES('5',200,'C');
INSERT INTO TEST_DATA VALUES('4',50,'B');
INSERT INTO TEST_DATA VALUES('5',200,'C');
INSERT INTO TEST_DATA VALUES('6',100,'A');
INSERT INTO TEST_DATA VALUES('2',50,'C');
INSERT INTO TEST_DATA VALUES('6',100,'A');
INSERT INTO TEST_DATA VALUES('2',100,'C');
INSERT INTO TEST_DATA VALUES('6',100,'A');
INSERT INTO TEST_DATA VALUES('2',100,'C');
INSERT INTO TEST_DATA VALUES('6',50,'A');
INSERT INTO TEST_DATA VALUES('2',200,'C');

 SELECT team,
        SUM(weight) AS total_weight
   FROM   (   SELECT id,
                     CASE WHEN @ID = ID THEN @ROW_NUMBER := @ROW_NUMBER + 1
                          ELSE @ROW_NUMBER := 1     
                      END AS rn,
                     team,
                     weight,
                     @id := id
                FROM TEST_DATA,
                     (SELECT @ROW_NUMBER := 1, @ID := '') r
               ORDER 
                  BY id, 
                     weight DESC
          ) TMP
 WHERE rn <= 3
   AND team <> ''
 GROUP
    BY team
 ORDER
    BY total_weight DESC;