[英]How to add 2 columns to existing query result based on another query?
I have a query like this:我有一个这样的查询:
SELECT
field1 as field1 ,
field2 as field2 ,
(select count(*) from ... where ...=field1) as field3
FROM
...
And it works fine - and I see 3 columns in results它工作正常 - 我在结果中看到 3 列
The I need to add one more column for internal query:我需要为内部查询再添加一列:
SELECT
field1 as field1 ,
field2 as field2 ,
(select count(*) as my_count, sum(*) as my _sum from ...where ...=field1 ) as field3
FROM
...
this syntax doesn't work.这种语法不起作用。
How can I achieve it?我怎样才能实现它?
This partial query makes it unsure what you really want, but I would expect that the subquery actually correlates to the outer query (otherwise, you could just cross join
).这个部分查询使它不确定你真正想要什么,但我希望子查询实际上与外部查询相关(否则,你可以只是
cross join
)。 If so, a typical solution is a lateral join.如果是这样,典型的解决方案是横向连接。
In Postgres:在 Postgres 中:
select
field1 as field1,
field2 as field2,
x.*
from ...
left join lateral (
select count(*) as my_count, sum(*) as my _sum from ...
) x
Oracle supports lateral joins starting version 12. You just need to replace left join lateral
with outer apply
. Oracle 从版本 12 开始支持横向连接。您只需要将
left join lateral
joinlateral 替换为outer apply
。
The following would seem to do what you want, and it should work fine in Oracle 9i:以下似乎可以满足您的要求,并且在 Oracle 9i 中应该可以正常工作:
SELECT t.field1,
t.field2,
x.my_count,
x.my_sum
FROM SOME_TABLE t
LEFT OUTER JOIN (select FIELD1,
count(*) as my_count,
sum(SOME_FIELD) as my_sum
from SOME_OTHER_TABLE
GROUP BY FIELD1) x
ON x.FIELD1 = t.FIELD1
You can use a CTE (Common Table Expression) to precompute the values:您可以使用 CTE(公用表表达式)来预先计算值:
WITH
q as (select count(*) as my_count, sum(*) as my _sum from ... )
SELECT
field1 as field1 ,
field2 as field2 ,
q.my_count as field3,
q.my_sum as field4
FROM
...
CROSS JOIN q
Or... you can always use the less performant, simpler way:或者...您始终可以使用性能较低、更简单的方法:
SELECT
field1 as field1 ,
field2 as field2 ,
(select count(*) from ... ) as field3,
(select sum(*) from ... ) as field4
FROM
...
With your limited (& a bit confusing - 2 databases, sum(*)...) info,由于您有限(有点混乱 - 2 个数据库,总和(*)...)信息,
here is the logic:这是逻辑:
SELECT
field1 as field1 ,
field2 as field2 ,
(select count(*) from ... ) as my_count,
(Select sum(<my field>) from ...) as my _sum
FROM
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.