SUM(some_column)WHERE some_column匹配

时间:2013-08-21 16:00:33

标签: mysql

所以我有一个表,我正在尝试获取SUM(activity_weight)WHERE activity_typeid是唯一的。

每场比赛都有无限量的activity_typeid。

正如您在下面的代码中所看到的,我想知道是否有一些SQL函数可以找到某些内容的SUM,例如id是唯一的?

感谢任何提前帮助!

我附上了我的桌子的照片和

下面的所需输出

enter image description here

 SELECT a.userid, u.name, u.profilePic , 
  SUM(activity_weight) AS totalPoints , 

  //sum the points when the activity_typeid is unique and make an extra column for each of those sums
  SUM(CASE WHEN activity_typeid //is unique// THEN activity_weight    ELSE NULL END) AS specific_points , 

  FROM activity_entries a INNER JOIN users1 u ON u.id = a.userid 

  WHERE competitionId = '$competitionId' GROUP BY a.userid ORDER BY totalPoints

3 个答案:

答案 0 :(得分:0)

SELECT SUM(something), ... FROM table t1 WHERE NOT EXISTS
(
    SELECT id FROM table t2 WHERE t1.id <> t2.id AND t1.checkfield = t2.checkfield
)
GROUP BY ...

基本上,您希望选择在checkfield中具有值的所有记录的总和,其中不存在具有该字段的相同值的记录。这样做很简单:只需查看同一个表中是否有相同值但ID不同的记录。

但是,我不确定这是你想要的。这只总结了独特的记录。如果活动ID不是唯一的,则根本不包括活动ID,甚至不包括一次。

答案 1 :(得分:0)

您可以尝试:

GROUP BY ...
HAVING SUM(activity_weight) AND COUNT(activity_typeid)=1

聚合函数仅用于比较HAVING子句

答案 2 :(得分:0)

从图像看起来你想要一个支点,我相信你通过做

来实现这一目标
SELECT a.userid, u.name, u.profilePic,
    SUM(activity_weight) total_points,
    SUM(CASE WHEN activity_typeid=22 THEN activity_weight ELSE 0 END) activity22,
    SUM(CASE WHEN activity_typeid=33 THEN activity_weight ELSE 0 END) activity33,
    SUM(CASE WHEN activity_typeid=55 THEN activity_weight ELSE 0 END) activity55    
FROM activity_entries a 
INNER JOIN users1 u ON u.id = a.userid 
WHERE competitionId = '$competitionId' 
GROUP BY a.userid 
ORDER BY totalPoints

编辑注释:以下可能存在一些语法错误,但想法是动态创建sql然后执行它

-- generate sql for pivoted columns
SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(CASE WHEN activity_typeid=',activity_typeid,
      ' THEN activity_weight ELSE 0 END) AS activity_', activity_typeid, 
    )
  ) INTO @sql
FROM activity_entries;

-- place above in full select query
-- n.b. the `$competitionId` could be a problem my MySQL is not v. good
SET @sql = CONCAT('SELECT a.userid, u.name, u.profilePic,
                          SUM(activity_weight) total_points,', @sql,
                  'FROM activity_entries 
                   JOIN users1 u ON u.id = a.userid 
                   WHERE competitionId = ''$competitionId''   
                   GROUP BY a.userid, u.name, u.profilePic
                   ORDER BY totalPoints');

-- execute the dynamic sql
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;