sql - SQL合并两个查询并为微积分插入一个新列
问题描述
我有 2 个表,Transactions
(感兴趣的属性:disponent_id,transaction_id)和Attachments
(感兴趣的属性:disponent_id,文件名)。
主要目标如下:
我想对表“Transact”的每个 Disponent 的事务进行分组(每个 Disponent 的事务)
- 与“附加”表相同(每个组件的附件)
- 之后,我想合并两者并插入一个新列,该列显示每个事务的附件比率(附件/事务)
- ..
(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
...
如何插入计算和附件列?
解决方案
我在子句中使用了您的查询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;
推荐阅读
- c# - 我可以在 C# 的 for 循环中跳过赋值语句吗?
- java - 如何使用 openapi-generator 为打开的 API 规范文件生成模拟
- javascript - 类型页面是 2 个模块错误声明的一部分
- html - 如何使我的网页上的文本可选?
- python - 我的 Codekata 解决方案提供了正确的解决方案,但在最终测试用例中遇到了性能问题
- bash - 有没有办法在我的 shell 脚本中并排运行两个命令?
- python - Scrapy 输出项 - 多种解析方法,每项一行
- cuda - 离开函数时消耗的 CUDA 内存
- html5-canvas - 为什么 requestAnimationFrame() 在一帧结束时运行我的代码,而不是在开始时?
- python - 尝试从此网站获取 JSON 时出错