如何从结果数据Oracle SQL聚合?

时间:2016-10-07 06:07:10

标签: sql oracle oracle10g

我有桌子:

+------+-------+-----------------+
| id   | name  | code   | desc   |
+------+-------+-----------------+
| 1    | aa    | 032016 | grape  |
| 1    | aa    | 012016 | apple  |
| 1    | aa    | 032016 | grape  |
| 1    | aa    | 022016 | orange |
| 1    | aa    | 012016 | apple  |
| 1    | aa    | 032016 | grape  |
+------+-------+-----------------+

我试过查询:

SELECT id, name, code, desc, COUNT(code) as view
FROM mytable
GROUP BY id, name, code, desc

结果是:

+------+-------+------------------------+
| id   | name  | code   | desc   | view |
+------+-------+------------------------+
| 1    | aa    | 012016 | apple  | 2    |
| 1    | aa    | 022016 | orange | 1    |
| 1    | aa    | 032016 | grape  | 3    |
+------+-------+------------------------+

我的期望是这样的:

+------+-------+----------------------------------------------------+
| id   | name  | code                 | desc               | view   |
+------+-------+----------------------------------------------------+
| 1    | aa    | 012016,022016,032016 | apple,orange,grape | 2,1,3  |
+------+-------+----------------------------------------------------+

任何人都可以帮我如何汇总结果吗? 提前谢谢

1 个答案:

答案 0 :(得分:2)

你的桌面设计让我有点担心。一个水果在表中总是有相同的代码是巧合吗?那为什么要冗余存储呢?应该有一个水果桌,每个水果及其代码只有一次。你知道为什么这被称为关系数据库系统,不是吗?

但是,根据您的查询,您几乎可以获得所需内容。您有每个ID,名称,代码和desc的计数。现在你想进一步聚合。所以在下一步中按ID和名称分组,因为你想要每个id和名称一个结果行。使用LISTAGG连接组中的字符串:

SELECT 
  id, 
  name, 
  listagg(code, ',') within group(order by code) as codes,
  listagg(desc, ',') within group(order by code) as descs,
  listagg(view, ',') within group(order by code) as views
FROM
(
  SELECT id, name, code, desc, COUNT(*) as view
  FROM mytable
  GROUP BY id, name, code, desc
)
GROUP BY id, name
ORDER BY id, name;