0

我正在构建以下帖子中的 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

谢谢你的帮助

4

1 回答 1

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
于 2012-09-06T15:00:32.020 回答