每个帐户的运行计数查询

时间:2012-05-23 07:51:15

标签: sql database oracle

我正在研究Gerrit的一些扩展。我有以下查询来从gerrit DB获取特定ACCOUNT_ID的TOTAL COMMITS,TOTOAL REVIEW COMMENTS ...等。

with 
  changeids as
    (select change_id from PATCH_SETS where UPLOADER_ACCOUNT_ID=1001961),
  patchcommentstoothers as
    (select count(*) c from patch_comments where AUTHOR_ID!=1001961 AND Change_id in (select change_id from changeids)),
  ownerchanges as
    (select count(*) c from changes where owner_account_ID=1001961 and OPEN='Y'),
  changemessages as
    (select count(*) c from change_messages where AUTHOR_ID=1001961 and change_id not in (select change_id from changeids))
select pcto.c TOT_PATCH_COMMENTS, oc.c TOT_CHANGES, cm.c TOT_CHANGE_MESSAGES
from patchcommentstoothers pcto, ownerchanges oc, changemessages cm;

现在通过上述查询,我​​可以获得一个用户的三个计数。我想为所有ACCOUNT_ID运行上面的查询。比如为每个帐户运行此查询(不仅仅是1001961),并为所有帐户一次性取回所有记录。

ACCOUNT表包含以下列:

"REGISTERED_ON" TIMESTAMP (6) NOT NULL ENABLE,
"FULL_NAME"       VARCHAR2(255 BYTE),
"PREFERRED_EMAIL" VARCHAR2(255 BYTE),
"CONTACT_FILED_ON" TIMESTAMP (6),
"MAXIMUM_PAGE_SIZE"   NUMBER(6,0) DEFAULT 0,
"SHOW_SITE_HEADER"    CHAR(1 BYTE) DEFAULT 'N',
"USE_FLASH_CLIPBOARD" CHAR(1 BYTE) DEFAULT 'N',
"DOWNLOAD_URL"        VARCHAR2(20 BYTE),
"DOWNLOAD_COMMAND"    VARCHAR2(20 BYTE),
"COPY_SELF_ON_EMAIL"  CHAR(1 BYTE) DEFAULT 'N',
"DATE_FORMAT"         VARCHAR2(10 BYTE),
"TIME_FORMAT"         VARCHAR2(10 BYTE),
"INACTIVE"            CHAR(1 BYTE) DEFAULT 'N',
"ACCOUNT_ID"          NUMBER(11,0) DEFAULT 0

我不想使用程序。

P.S。 - 我厌倦了Oracle SQL。

1 个答案:

答案 0 :(得分:1)

with
  changeids
as
(
  select
    UPLOADER_ACCOUNT_ID,
    change_id
  from
    PATCH_SETS
  group by
    UPLOADER_ACCOUNT_ID,
    change_id
),
  patchcommentstoothers
as
(
  select
    changeids.UPLOADER_ACCOUNT_ID,
    count(*) c
  from
    changeids
  inner join
    patch_comments
      ON  changeids.UPLOADER_ACCOUNT_ID != patch_comments.AUTHOR_ID
      AND changeids.change_id            = patch_comments.change_id
  group by
    changeids.UPLOADER_ACCOUNT_ID 
),
  ownerchanges
as
(
  select
    owner_account_ID,
    count(*) c
  from
    changes
  where
    OPEN='Y'
  group by
    owner_account_ID
),
  changemessages
as
(
  select
    change_messages.AUTHOR_ID,
    count(*) c
  from
    change_messages
  left join
    changeids
      on  changeids.UPLOADER_ACCOUNT_ID = change_messages.AUTHOR_ID
      AND changeids.change_id           = change_messages.change_id
  where
    changeids.change_id IS NULL
  group by
    change_messages.AUTHOR_ID
)

select
  accounts.ACCOUNT_ID,
  pcto.c   TOT_PATCH_COMMENTS,
  oc.c     TOT_CHANGES,
  cm.c     TOT_CHANGE_MESSAGES
from
  accounts
LEFT JOIN
  patchcommentstoothers pcto
    ON accounts.ACCOUNT_ID = pcto.UPLOADER_ACCOUNT_ID
LEFT JOIN
  ownerchanges          oc
    ON accounts.ACCOUNT_ID = oc.owner_account_ID
LEFT JOIN
  changemessages        cm
    ON accounts.ACCOUNT_ID = cm.AUTHOR_ID
;

CTE现在计算每个用户的值。

最终选择假设您有一个列出所有用户的user表。

如果您按用户过滤最终查询,CTE将仅计算最终结果中用户的结果。