使用group by with inner join和count

时间:2014-10-21 08:24:57

标签: sql oracle

我想列出与account_group_profile_test表格在一对多关系中的account_group_physician_aff_t的所有详细信息都包含AMDM_ACCOUNT_GROUP_ID column,这是account_group_profile_test表I的主键想要显示account_group_profile_test的所有记录,并计算account_group_physician_aff_t表中AMDM_ACCOUNT_GROUP_ID column(外键)中具有相同值的记录数

我正在使用以下查询,但它显示出一些错误。

SELECT ag_pro.*, 
       Count(ag_phy_aff.account_group_physician_aff_id) 
FROM   account_group_profile_test ag_pro 
       inner join account_group_physician_aff_t ag_phy_aff 
               ON 
       ag_phy_aff.amdm_account_group_id = ag_pro.amdm_account_group_id 
GROUP  BY ag_pro.amdm_account_group_id 

2 个答案:

答案 0 :(得分:1)

您的错误消息可能与您尝试显示表account_group_profile_test中的所有列(选择ag_pro.*)有关,但它们未在GROUP BY子句中列出。

你可以这样做: 选择account_group_profile_test中的所有记录,其中account_group_physician_aff_t中的记录数与amdm_account_group_id匹配

SELECT ag_pro.*, 
       (
           SELECT  count(*)
           FROM    account_group_physician_aff_t ag_phy_aff
           WHERE   ag_phy_aff.amdm_account_group_id = ag_pro.amdm_account_group_id
       ) "count of ag_phy_aff"
FROM   account_group_profile_test ag_pro

答案 1 :(得分:0)

根据问题的上半部分,以下查询应执行正确的操作:

select ag_pro.*,
       X.aff_t_count
FROM account_group_profile_test ag_pro
INNER JOIN
(
    SELECT 
    amdm_account_group_id,
    count(*) as aff_t_count
    FROM account_group_physician_aff_t
    group by amdm_account_group_id
) X
on ag_pro.amdm_account_group_id = X.amdm_account_group_id

您只需要aff_t表中的记录数,因此首先执行子选择,然后将结果加入到完整的ag_pro表中。

这只会返回两个表中amdm_account_group_id的值。要确保保留该列的所有值,即使它们未显示在aff_t表中,也请将INNER JOIN替换为LEFT JOIN,并处理任何NULL包含CASE块的值:

select ag_pro.*,
       CASE WHEN X.aff_t_count is NULL then 0
       ELSE X.aff_t_count 
       END as aff_t_count

FROM account_group_profile_test ag_pro
LEFT JOIN
(
    SELECT 
    amdm_account_group_id,
    count(*) as aff_t_count
    FROM account_group_physician_aff_t
    group by amdm_account_group_id
) X
on ag_pro.amdm_account_group_id = X.amdm_account_group_id