在同一日期多次出现时的Oracle计数

在同一日期多次出现时的Oracle计数,oracle,count,subquery,Oracle,Count,Subquery,这就是我想要做的 计算id代码多次出现时的不同日期数 ex: id,site,code,date 1,01,A,08/20/2012 2,01,A,08/21/2012 1,01,A,08/20/2012 这是我认为它会是什么样子,但显然是错的…如果我没有任何意义,请告诉我。谢谢你调查这件事 SELECT id, site, code, (select count(distinct date) from table b where code = 'A' and b.id = a.id

这就是我想要做的

计算id代码多次出现时的不同日期数

ex:
id,site,code,date
1,01,A,08/20/2012
2,01,A,08/21/2012
1,01,A,08/20/2012
这是我认为它会是什么样子,但显然是错的…如果我没有任何意义,请告诉我。谢谢你调查这件事

SELECT 
id,
site,
code,
(select count(distinct date)
  from table b
  where code = 'A' and b.id = a.id and count(distinct date) > 2) subquery
from table a


result goal:
1,01,A,1
2,01,A,0 or null

我将使用一个子查询来实现这一点,该子查询按id和日期进行聚合,然后再按id进行聚合:

select t.*, tsum.numTwiceOrMore
from (select distinct id, site, code
      from t
     ) t join
     (select id, sum(case when cnt > 1 then 1 else 0 end) as numTwiceOrMore
      from (select id, date, count(*) as cnt
            from t
            group by id, date
           ) tsum
      group by id
     ) tsum
     on t.id = tsum.id

您不能在计算聚合的查询的
where
子句中引用聚合;但这就是
having
子句的目的:

SELECT id, site, code,
    (select count(distinct date)
    from table b
    where code = 'A' and b.id = a.id
    having count(distinct date) > 2) subquery
from table a;
但无论如何,不要认为这会得到你想要的;不清楚是否要显示任何
id
(和
site
,以及
code
?您使用的标准是什么?)的整行,其中的条目超过一天,或者仅显示日期计数


好吧,我想我已经明白你的意思了。。。如果一个
id
code
多次出现,您只想显示日期数,大概是在任何站点上?你可以用这个;例如,使用CTE获取您提供的数据:

with t as (
    select 1 as id, '01' as site, 'A' as code, date '2012-08-20' dt from dual
    union all select 2, '01', 'A', date '2012-08-21' from dual
    union all select 1, '01', 'A', date '2012-08-20' from dual
)
SELECT distinct id, site, code,
    case when code_count_for_id > 1 then dt_count else null end as dates
FROM (
    SELECT id, site, code, dt,
        count(distinct dt) over (partition by id, code) dt_count,
        count(*) over (partition by id, code) as code_count_for_id
    FROM t
)
ORDER BY id, code;

        ID SI C      DATES
---------- -- - ----------
         1 01 A          1
         2 01 A
因此,在内部查询中,
dt\u count
被计算为
id
code
组合的不同日期数,而
code\u count\u被计算为该组合出现的次数


然后在外部查询中,
大小写
决定是显示
dt\u count
还是显示
null
,这取决于
code\u count\u for\u id

您的输出与您要求的查询不匹配。每个ID只有一个不同的日期,但每行的编号不同。
with t as (
    select 1 as id, '01' as site, 'A' as code, date '2012-08-20' dt from dual
    union all select 2, '01', 'A', date '2012-08-21' from dual
    union all select 1, '01', 'A', date '2012-08-20' from dual
)
SELECT distinct id, site, code,
    case when code_count_for_id > 1 then dt_count else null end as dates
FROM (
    SELECT id, site, code, dt,
        count(distinct dt) over (partition by id, code) dt_count,
        count(*) over (partition by id, code) as code_count_for_id
    FROM t
)
ORDER BY id, code;

        ID SI C      DATES
---------- -- - ----------
         1 01 A          1
         2 01 A