Oracle SQL-同一年按功能分组的列表不止一次

时间:2019-12-09 19:49:59

标签: sql oracle

select extract( year from "date" ),count(id)    
  from table1 e 
  left join table2 w
    on e.differentid = w.differentid -- (different id is in both tables, ‘id’ is not)    
 where regexp_like(id, '^[[:digit:]]+$')    
 group by "date", extract( year from "date" )
 order by "date";

我正在使用上面的代码创建一个包含3个字段的表。一个带年份,一个带ID的计数仅包含数字,另一个带数字和字母的计数ID。

group by不会每年将其排成一行,而是几年会出现多次。

1 个答案:

答案 0 :(得分:1)

您正在按date进行汇总。您需要将其从group by中删除:

select extract(year from date),
       sum(case when REGEXP_LIKE(id, '^[[:digit:]]+$') then 1 else 0 end ) as only_digits,
       sum(case when REGEXP_LIKE(id, '^[[:alpha:][:digit:]]+$') then 1 else 0 end ) as only_alphadigits,
from table1 e left join
     table2 w
     on e.differentid = w.differentid  -- (different id is in both tables, ‘id’ is not)    
group by extract(year from date)
order by min(DATE);

group by中的键定义结果集中的行。键值的每个唯一组合都会在结果集中产生一个行。显然,“年”内date有多个行。通过包含date,您可以分别获取每一行。