多行具有相同值的列的和

时间:2016-01-27 21:23:25

标签: mysql

我试图从共享相似数据的所有行中获取单个列的总和。例如,给出以下数据:

|ppID | cID   | Count | NameSpace|
|-----|-------|-------|----------|
|586  | 18281 | 1     | LAB      |
|587  | 18269 | 1     | LAB      |
|588  | 18281 | 1     | LAB      |
|589  | 17823 | 1     | IPB      |
|590  | 18281 | 1     | LAB      |
|591  | 18256 | 1     | LAB      |
|592  | 18256 | 1     | LAB      |
|593  | 18269 | 1     | IPB      |
|-----|-------|-------|----------|

我希望得到:

|ppID | cID   | Count | NameSpace|
|-----|-------|-------|----------|
|586  | 18281 | 3     | LAB      |
|587  | 18269 | 1     | LAB      |
|589  | 17823 | 1     | IPB      |
|591  | 18256 | 2     | LAB      |
|593  | 18269 | 1     | IPB      |
|-----|-------|-------|----------|

我把几件不同的东西拼凑在一起,然后提出“

SELECT * FROM PopularPages 
WHERE cID IN (SELECT cID FROM PopularPages 
              GROUP BY cID 
              HAVING COUNT(cID) > 1) 
ORDER BY cID, Namespace

将列出每一行但不计算Count列的总和。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

这就是你想要的吗?

SELECT
  MIN(ppID) as ppID,
  cID,
  SUM(`Count`) as COUNT,
  NameSpace
FROM PopularPages
GROUP BY cID
HAVING Count > 1;