2

我在 Oracle 数据库中有以下数据:

Name    Place     Color
------- --------- --------
John    Paris     Blue
John    Miami     Blue
Ryan    Boston    Red
Ryan    Boston    Red
Jim     Miami     Blue
Ryan    Oslo      Red
Jason   Rome      Green
Jim     Paris     Blue
Jason   Rome      Green
Jim     Paris     Blue
Ryan    Boston    Red

如果两列相同(名称/地点),我需要重复数据删除,然后按第三列计数。我正在尝试使用嵌套选择按两次分组,但我不断收到 ORA-00933 错误。

select Color, count(Color)
from
(
    select TO_CHAR(Name)||'-'||(Place) as unique_ident from mytable
    group by TO_CHAR(Name)||'-'||(Place)
) as inline
group by Color


我会返回类似的东西

Blue   4
Red    2
Green  1

任何帮助表示赞赏。

4

3 回答 3

2

我想你正在寻找这样的东西:

SELECT Color, COUNT(DISTINCT name || '-' || place) ColorCnt
FROM yourtable
GROUP BY Color

导致:

COLOR   ColorCnt
-----------------
Green   1
Blue    4
Red     2
于 2013-05-31T23:14:17.750 回答
0

sgeddes 的回答很好。您的查询的问题是您的外部查询引用color了 ,但它不在您的内部查询中。您可以通过以下方式解决此问题:

select Color, count(Color)
from (select TO_CHAR(Name)||'-'||(Place) as unique_ident, color
      from mytable
      group by TO_CHAR(Name)||'-'||(Place), color
     ) as inline 
group by Color;

然而,该count(distinct)配方可能更可取。

于 2013-05-31T23:24:29.630 回答
0

这不是给你想要的结果吗?

select TO_CHAR(Name)||'-'||(Place) , color, count(*) as color_count
from mytable
group by name, place, color
于 2013-05-31T23:12:37.933 回答