MS Access SQL从表1中选择原始连接表2选择匹配

时间:2018-02-05 16:57:37

标签: sql ms-access

我在表Master中有来自银行的交易列表,每个交易都有一个唯一的masterID。然后,这些事务由用户分成日记条目,这些日志条目存储在表Master_Split中。 Master_Split表有一个名为import_Master_ID的外键字段,它将两个表连接在一起。

我尝试创建一个选择Master记录的查询,并以相同的格式拆分记录。

最初我使用了右连接,因为只需要拆分条目。但是,现在要求已经改变了,我不确定我应该研究哪些技术/关键词。您可以在第三个表中看到所需的输出。

任何指导,甚至指出我正确的方向将不胜感激。如果有任何关于这个问题的信息不清楚,请告诉我,谢谢你提前寻求帮助。

SELECT 
M.[masterID], M.[OrigAcctNum], S.[NewAcctNum], S.[PostAmnt]
FROM Master M
RIGHT JOIN Master_Split S ON M.[masterID] = S.[import_Master_ID]`

Master table +----------+---------+----------+ | masterID | AcctNum | PostAmnt | +----------+---------+----------+ | 1 | 99999 | 150 | +----------+---------+----------+ | 2 | 88888 | 200 | +----------+---------+----------+

Master_Split +------------------+-----------+-----------+ | import_master_ID | SplitAcct | SplitAmnt | +------------------+-----------+-----------+ | 1 | 12345 | -50 | +------------------+-----------+-----------+ | 1 | 54321 | -100 | +------------------+-----------+-----------+ | 2 | 11111 | -175 | +------------------+-----------+-----------+ | 2 | 22222 | -25 | +------------------+-----------+-----------+

Result +----------+-------------+------------+----------+--------+ | masterID | OrigAcctNum | NewAcctNum | PostAmnt | Status | +----------+-------------+------------+----------+--------+ | 1 | 99999 | 99999 | 150 | Orig | +----------+-------------+------------+----------+--------+ | 1 | 99999 | 12345 | -50 | Split | +----------+-------------+------------+----------+--------+ | 1 | 99999 | 54321 | -100 | Split | +----------+-------------+------------+----------+--------+ | 2 | 88888 | 88888 | 200 | Orig | +----------+-------------+------------+----------+--------+ | 2 | 88888 | 11111 | -175 | Split | +----------+-------------+------------+----------+--------+ | 2 | 88888 | 22222 | -25 | Split | +----------+-------------+------------+----------+--------+

2 个答案:

答案 0 :(得分:1)

UNION ALL将在一个结果集中为您提供两组信息:

SELECT 
M.[masterID], M.[OrigAcctNum], M.[NewAcctNum], M.[PostAmnt], 'Orig' AS [Status]
FROM Master M
UNION ALL
SELECT 
M2.[masterID], M2.[OrigAcctNum], S.[NewAcctNum], S.[PostAmnt], 'Split' AS [Status]
FROM Master M2
RIGHT JOIN Master_Split S ON M2.[masterID] = S.[import_Master_ID]`

答案 1 :(得分:1)

像这样的东西可以做这个工作..抱歉写在没有垫5分钟之前去回家..

    select * from 
    (
            select 
                masterID as ID,  AcctNum  as OrigAcctNum,  AcctNum  as NewAcctNum,  PostAmnt,  'Orig' as Status
            from Master 
        union all
            select 
                ms.import_master_ID  as ID,  m.AcctNum  as OrigAcctNum,  ms.SplitAcct as NewAcctNum,  ms.SplitAmnt as PostAmnt,  'Split' as Status
            from Master_Split ms
                join Master m on m.masterID = ms.import_master_ID
            where
    )
    order by ID