MySQL - 如何根据用户ID合并行并生成SUM

时间:2016-01-05 09:18:16

标签: php mysql sql

我写了以下MySQL select查询:

SELECT cs.id, cs.campaign_id, cs.instagram_id, cs.media_id, cs.has_tag, cs.comments_count, cs.likes_count, DATE(cs.created_date) AS created_date, sl.username, (cs.comments_count + cs.likes_count) AS total_comments_likes
FROM campaign_statistic AS cs 
LEFT JOIN social_login AS sl ON sl.social_id = cs.instagram_id
WHERE instagram_id IN (481959735, 12095962) 
AND has_tag = 'sometag' 
ORDER BY created_date ASC

得到这个结果:

enter image description here

现在您可以看到2015-12-10中有三个条目:

id  campaign_id     instagram_id    media_id                         has_tag     comments_count     likes_count     created_date    username    total_comments_likes
66  50              481959735       1110926795500814980_481959735    sometag     1                  51              2015-12-10      myname      52
74  50              12095962        1102652300222991882_12095962     sometag     0                  16              2015-12-10      myname      16
77  50              481959735       1096415071007540220_481959735    sometag     0                  18              2015-12-10      myname      18

您可以看到481959735 Instagram id当天有两条记录(2015-12-10)。现在我想要SUM comments_count& likes_count 481959735 并合并在一行。

我想要这个输出:

id  campaign_id     instagram_id    media_id                         has_tag     comments_count     likes_count     created_date    username    total_comments_likes
66  50              481959735       1110926795500814980_481959735    sometag     1                  69              2015-12-10      myname      70
74  50              12095962        1102652300222991882_12095962     sometag     0                  16              2015-12-10      myname      16

任何想法如何使用mysql查询。

由于

2 个答案:

答案 0 :(得分:1)

用于SUM的USE Group By子句和SUM函数

查询将是

  

SELECT cs.campaign_id,cs.instagram_id,Sum(cs.comments_count),   SUM(cs.likes_count),Sum(cs.comments_count)+ SUM(cs.likes_count)AS   total_comments_likes FROM campaign_statistic AS cs LEFT JOIN   social_login AS sl ON sl.social_id = cs.instagram_id WHERE   cs.instagram_id IN(481959735,12095962)AND has_tag =' sometag'   group by cs.campaign_id,cs.instagram_id ORDER BY created_date ASC

答案 1 :(得分:0)

你可以总结()所需的字段。这适用于group by cs.instagram_id

SELECT
  cs.id,
  cs.campaign_id,
  cs.instagram_id,
  cs.media_id,
  cs.has_tag,
  sum(cs.comments_count) as comments_count,
  sum(cs.likes_count) as likes_count,
  DATE(cs.created_date) AS created_date,
  sl.username,
  sum(cs.comments_count + cs.likes_count) AS total_comments_likes
FROM campaign_statistic AS cs 
LEFT JOIN social_login AS sl ON sl.social_id = cs.instagram_id
WHERE instagram_id IN (481959735, 12095962) 
AND has_tag = 'sometag' 
group by cs.instagram_id
ORDER BY created_date ASC