首页 > 解决方案 > SQL合并两个查询并为微积分插入一个新列

问题描述

我有 2 个表,Transactions(感兴趣的属性:disponent_id,transaction_id)和Attachments(感兴趣的属性:disponent_id,文件名)。

主要目标如下:

我想对表“Transact”的每个 Disponent 的事务进行分组(每个 Disponent 的事务)

  1. 与“附加”表相同(每个组件的附件)
  2. 之后,我想合并两者并插入一个新列,该列显示每个事务的附件比率(附件/事务)
  3. ..
(1)
Disponent | Transactions
213456    | 35
...

(2)
Disponent | Attachments
213456    | 70

(3)
Disponent | Transactions | Attachments | Ratio
213456    | 35           | 70          | 2
...

我试过了

SELECT Transact.disponent_id, COUNT(Transact.transaction_id) AS Transactionnumber
FROM Transact
GROUP BY Transact.disponent_id
UNION ALL
SELECT Attach.disponent_id, COUNT(Attach.filename) AS Filenumber
FROM Attach
GROUP BY Attach.disponent_id

但结果只有:

disponent_id | transactionnumber
234576 | 65
...

如何插入计算和附件列?

标签: sql

解决方案


我在子句中使用了您的查询with,然后使用带有内部联接的新选择语句。

一探究竟:

With wth0 as 
(
    SELECT 
      Transact.disponent_id, 
      COUNT(Transact.transaction_id) AS Transactionnumber
    FROM Transact
    GROUP BY Transact.disponent_id
), 
wth1 as 
(
    SELECT Attach.disponent_id, COUNT(Attach.filename) AS Filenumber
    FROM Attach
    GROUP BY Attach.disponent_id
)
SELECT 
  wth0.disponent_id,
  wth0.Transactionnumber,
  wth1.Filenumber,
  wth1.Filenumber / wth0.Transactionnumber as Ratio
from wth0
inner join wth1 
  on wth0.disponent_id = wth1.disponent_id;

推荐阅读