MySQL:根据ID选择前5行,找到小计

时间:2018-03-13 05:55:22

标签: mysql

需要根据特定列的值desc值为每个id选择前5行,并查找该列的小计。例如(尝试创建情境,实际表结构很大

ID  VALUE   
1   2       
1   3       
1   4       
1   5       
1   6       
1   7       
1   8       
2   9       
2   10      
2   11      
2   12      
2   13      
2   14  

预期输出

ID     VALUE
1        8
1        7
1        6
1        5
1        4
TOTAL   30
2       14
2       13
2       12
2       11
2       10
TOTAL   60

我可以使用像这样的代码选择前5行;

@cust_rank := IF(@current_cust = id, @cust_rank + 1, 1) AS cust_rank,
                 @current_cust := id

然后选择前5名

另外,我可以使用这样的代码小计;

SELECT id, value FROM source
UNION
SELECT NULL,SUM(value) FROM source
GROUP BY id ORDER BY id; 
  

我需要合并两个要求。

1 个答案:

答案 0 :(得分:1)

SELECT CAST(id as CHAR(50)) Id, value
FROM (SELECT id , value ,
             IF(@lastid=(@lastid:=id), @auto:=@auto+1, @auto:=1) indx 
      FROM source, (SELECT @lastid:=0, @auto:=1) A 
      ORDER BY id,value desc)as A  
WHERE indx <= 5

输出

Id  value
1   8
1   7
1   6
1   5
1   4
2   14
2   13
2   12
2   11
2   10

第二次查询

SELECT 'Total', SUM(value)
FROM (SELECT id , value ,
             IF(@lastid=(@lastid:=id), @auto:=@auto+1, @auto:=1) indx 
      FROM source, (SELECT @lastid:=0, @auto:=1) A 
      ORDER BY value desc)as A  
WHERE indx <= 5 
GROUP BY id ;

输出

Total   SUM(value)
Total   30
Total   60

合并查询:

Select 
CASE
    WHEN indx =6 THEN "Total"
    ELSE id
END as ID,value
from
(
  select id,value,
IF(@lastid=(@lastid:=id), @auto:=@auto+1, @auto:=1) indx 
FROM
(
SELECT CAST(id as CHAR(50)) Id, value
FROM (SELECT id , value ,
             IF(@lastid=(@lastid:=id), @auto:=@auto+1, @auto:=1) indx 
      FROM source, (SELECT @lastid:=0, @auto:=1) A 
      ORDER BY id,value desc)as A  
WHERE indx <= 5
UNION
SELECT CAST(id as CHAR(50))as id, SUM(value)as value
FROM (SELECT id , value ,
             IF(@lastid1=(@lastid1:=id), @auto1:=@auto1+1, @auto1:=1) indx 
      FROM source, (SELECT @lastid1:=0, @auto1:=1) A 
      ORDER BY value desc)as A  
WHERE indx <= 5 
GROUP BY id)as output ,(SELECT @lastid:=0, @auto:=1) A ORDER BY id) as output1

输出

ID    value
1       8
1       7
1       6
1       5
1       4
Total   30
2       10
2       11
2       12
2       13
2       14
Total   60