获得所有行的总和

时间:2014-01-25 07:13:19

标签: mysql sql select group-by sum

我有一个类似下面的查询。我的目标是添加所有'total_points'并检索所有行总和的单个结果。

SELECT
SUM(
COALESCE(
CASE 
WHEN COUNT(DISTINCT `table_1`.views) > 50 OR  COUNT(DISTINCT `table_1`.views) = 50 AND COUNT(DISTINCT `table_1`.views) < 100 THEN COUNT(DISTINCT `table_1`.views) +5
ELSE COUNT(DISTINCT `table_1`.views)
END,0)
+

CASE 
WHEN COUNT(DISTINCT `table_2`.views) > 50 OR  COUNT(DISTINCT `table_2`.views) = 50 AND COUNT(DISTINCT `table_2`.views) < 100 THEN COUNT(DISTINCT `table_2`.views) +5
ELSE COUNT(DISTINCT `table_2`.views)
END,0)) AS sum

FROM  `table_1`
LEFT JOIN `table_2`
ON `table_1`.id = `table_2`.id
GROUP BY `table_1`.primary_id

这会给我一个像这样的结果

rank  | total_points
1          321
2          111
3          100
4          90         
5          72
6          60
7          45
8          23
9          11
10         5

这是我的愿望结果:

   sum   |
   838

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT IFNULL(rank, 'Sum') rank, total_points
FROM (SELECT @rank := @rank + 1 AS rank, T1.total_points
      FROM (SELECT COALESCE((CASE WHEN COUNT(DISTINCT t1.views) betwnn 50 AND 100 THEN COUNT(DISTINCT t1.views) + 5 ELSE COUNT(DISTINCT t1.views) END) + 
                  (CASE WHEN COUNT(DISTINCT t2.views) betwnn 50 AND 100 THEN    COUNT(DISTINCT t2.views) + 5 ELSE COUNT(DISTINCT t2.views) END), 0)  AS total_points
            FROM table_1 t1
            LEFT JOIN table_2 t2 ON t1.id = t2.id
            GROUP BY t1.primary_id
            ORDER BY total_points
          ) AS T1, (SELECT @rank := 0) AS r
      ORDER BY total_points DESC 
    ) AS A
GROUP BY rank WITH ROLLUP