联合中具有聚合函数的子查询

时间:2012-09-06 14:50:18

标签: sql sql-server-2008

我正在构建以下帖子中的SQl语句:Union two different tables with a primary ID field

有两个表(md_master& cd_personal_checks)我试图合并到一个视图中。 这是我目前的陈述。

CREATE VIEW ViewCR AS  

SELECT id  + 100000000000000000 AS id, a.external_code + CAST(id AS varchar(15)) as crUniqueId,
       m.check_amount, 'C' as crType, m.postprint_date as activationDate,
       m.postprint_date as creationDate, m.memo_explanation as reasonLine1, m.check_no
  FROM MD_Master m
  Join accounts a on m.account_tag = a.acct_id
 WHERE (m.postprint_tag = 2) OR (m.postprint_tag = 4) OR 
       (m.postprint_tag = 5) OR (m.postprint_tag = 7)

 UNION ALL 

SELECT id + 200000000000000000 as id, 'PERCHK' + CAST(id AS varchar(15)) as crUniqueId,
       check_amount, 'P' as crType, business_date as activationDate,
       business_date as creationDate, identify_description as reasonLine1, check_no
  FROM cd_personal_checks 

但是,我已经达到了另一个障碍。我需要从另一个表中获取数据(其中包含上述两个表中每个表的链接)

在上面的两个选择状态中,我需要添加一个名为“dispositionAmount”的字段,即check_amount - SUM(md_cr_pending.current_amount)

md_cr_pending表格中有一个与master_id相关联的md_master.id字段 md_cr_pending表格中有一个与cd_personal_check_id

相关联的cd_personal_checks.id字段

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

由于你没有发布第三个表和forignKeys我只能帮助解决这个问题:

CREATE VIEW ViewCR AS  

    SELECT id  + 100000000000000000 AS id, 
    a.external_code + CAST(id AS varchar(15)) as crUniqueId, 
    m.check_amount, 
    'C' as crType, 
    m.postprint_date as activationDate, 
    m.postprint_date as creationDate, 
    m.memo_explanation as reasonLine1, 
    m.check_no,
    m.check_amount - sh.sumAmount As Difference 
    FROM MD_Master m
    Join accounts a on m.account_tag = a.acct_id
    INNER JOIN (SELECT forignKeyID, 
                SUM(md_cr_pending.current_amount) as sumAmount 
                FROM Table 3
                Group BY forignKeyID) sh ON sh.forignKeyID = m.ID
    WHERE (m.postprint_tag = 2) OR (m.postprint_tag = 4) OR 
          (m.postprint_tag = 5) OR (m.postprint_tag = 7)

    UNION ALL 

    SELECT id + 200000000000000000 as id, 
    'PERCHK' + CAST(id AS varchar(15)) as crUniqueId, 
    check_amount, 
    'P' as crType, 
    business_date as activationDate, 
    business_date as creationDate, 
    identify_description as reasonLine1, 
    check_no,
    check_amount - sh.sumAmount As Difference 
    FROM cd_personal_checks 
    INNER JOIN (SELECT forignKeyID, 
                SUM(md_cr_pending.current_amount) as sumAmount 
                FROM Table 3
                Group BY forignKeyID) sh 
                ON sh.forignKeyID = cd_personal_checks.ID