0

这就是我想做的事情。

计算某个 id 的代码多次出现时的 DISTINCT 日期数。

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
4

3 回答 3

1
select "id", "site", "code", 
    count(distinct "date") - 1 as AdditionalDistinctDateCount
from MyTable
group by "id", "site", "code", "date"

SQL 小提琴示例

于 2012-09-05T15:58:23.577 回答
0

我会用一个按 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
于 2012-09-05T15:57:45.843 回答
0

您不能在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


好的,我想我已经明白你的意思了......你只想显示日期的数量,如果acode出现不止一次 a id,大概在任何网站上?您可以为此使用分析函数;使用 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_count计算为idandcode组合的不同日期数,并code_count_for_id计算为该组合出现的次数。

然后在外部查询中case决定是显示dt_count还是null取决于code_count_for_id.

于 2012-09-05T15:58:35.907 回答