SQL - 通过对 2 个表的连接结果进行计算来创建新列
SQL - creating new columns by making calculations on the result of a join of 2 tables
我有 2 个 select 查询是这样加入的:
select * from
(
select sum(checkedcrates.checkedcrates) as sumA, checkedcrates.paramdescription from
(another query...)
as checkedcrates
group by checkedcrates.paramdescription
)
as A
Join
(select sum(cratecnt.cnt) as sumB, cratecnt.paramdescription from
(yet another query... )
as cratecnt
group by cratecnt.paramdescription)
as B
on a.paramdescription = b.paramdescription order by B.sum desc
这个查询的结果是这样的:
sumA paramdescription sumB paramdescription
----------------------------------------------------------
1779 bottom 10 bottom
1779 totalarea 8 totalarea
1779 innerwalls 7 innerwalls
1779 risperror 1 risperror
1779 outerwalls 0 outerwalls
1779 clipserror 0 clipserror
1779 totalnumberdefects 0 totalnumberdefects
到目前为止一切顺利。现在我需要添加第五列,作为 sumB/sumA
的结果。我知道如何在一个简单的查询上执行此操作,但我不知道如何在连接后使用来自两个不同 select 查询的数据添加它。
只需将 b.sumB / a.sumA
添加到 select 列表:
select a.*, b.*, b.sumB / a.sumA from
...
也许您想 b.sumB * 1.0 / a.sumA
,以避免整数除法(取决于使用的 dbms。)
我有 2 个 select 查询是这样加入的:
select * from
(
select sum(checkedcrates.checkedcrates) as sumA, checkedcrates.paramdescription from
(another query...)
as checkedcrates
group by checkedcrates.paramdescription
)
as A
Join
(select sum(cratecnt.cnt) as sumB, cratecnt.paramdescription from
(yet another query... )
as cratecnt
group by cratecnt.paramdescription)
as B
on a.paramdescription = b.paramdescription order by B.sum desc
这个查询的结果是这样的:
sumA paramdescription sumB paramdescription
----------------------------------------------------------
1779 bottom 10 bottom
1779 totalarea 8 totalarea
1779 innerwalls 7 innerwalls
1779 risperror 1 risperror
1779 outerwalls 0 outerwalls
1779 clipserror 0 clipserror
1779 totalnumberdefects 0 totalnumberdefects
到目前为止一切顺利。现在我需要添加第五列,作为 sumB/sumA
的结果。我知道如何在一个简单的查询上执行此操作,但我不知道如何在连接后使用来自两个不同 select 查询的数据添加它。
只需将 b.sumB / a.sumA
添加到 select 列表:
select a.*, b.*, b.sumB / a.sumA from
...
也许您想 b.sumB * 1.0 / a.sumA
,以避免整数除法(取决于使用的 dbms。)