SQL合并两个查询并为微积分插入新列

时间:2019-01-14 15:48:34

标签: sql

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

主要目标如下:

我要对“交易”表中每个“异议人”的交易进行分组(每个异议人的交易)

  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
...

如何插入计算和附件列?

1 个答案:

答案 0 :(得分:0)

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

签出:

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;