function sum() 2 fields with same id

huangapple go评论63阅读模式
英文:

function sum() 2 fields with same id

问题

I am trying to get the sum of particular field. I am getting the SUM wrong when I try to get the values together.
I have this:

  • reference: id_skill, user, level_paid

More specifically the table reference as:

id_skill user level_paid
100 Red 1
100 Red 1
200 Red 2
200 Red 1

What I want as a result from my query is,

id_skill user level_paid
100 Red 2
200 Red 3
SELECT   
  SUM(level_paid) AS total,
FROM reference
WHERE user = 'Red'
GROUP BY 
  id_skill

What I am trying to achieve is to get the sum of the field "level_paid" if the records of "id_skill" is more than 1.

英文:

I am trying to get the sum of particular field. I am getting the SUM wrong when I try to get the values together.
I have this:

  • reference: id_skill, user, level_paid

More specifically the table reference as:

id_skill user level_paid
100 Red 1
100 Red 1
200 Red 2
200 Red 1

What I want as a result from my query is,

id_skill user level_paid
100 Red 2
200 Red 3
SELECT   
  SUM(level_paid) AS total,
FROM reference
WHERE user = 'Red'
GROUP BY 
  id_skill

What I am trying to achieve is to get the sum of the field "level_paid" if the records of "id_skill" is more than 1.

答案1

得分: -1

你可以通过以下查询来实现结果。HAVING 子句将确保您仅对基于 GROUP BY 条件,即至少有两个具有相同值的 id_skill 记录的值进行求和。

SELECT
  id_skill,   
  user,
  SUM(level_paid) AS level_paid
FROM reference
WHERE user = 'Red'
GROUP BY 
  id_skill, user
HAVING COUNT(*) > 1
英文:

You can achieve the result with the following query. The HAVING clause will ensure, you are only summing the values, which are more than 1 records, based on the GROUP BY condition e.g. at least two id_skill with the same value.

SELECT
  id_skill,   
  user,
  SUM(level_paid) AS level_paid
FROM reference
WHERE user = 'Red'
GROUP BY 
  id_skill, user
HAVING COUNT(*) > 1

huangapple
  • 本文由 发表于 2023年5月7日 04:03:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76190879.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定