在Oracle中,如果你想将一个SELECT语句作为字段的值,你可以使用子查询或者使用WITH子句(也称为公用表表达式CTE)。以下是两种方法的示例:
方法1:使用子查询
语法如下:
SELECT
column1,
(SELECT COUNT(*) FROM another_table WHERE another_table.column2 = table1.column1) AS count_value
FROM
table1;
实例:
SELECT
(SELECT a.companycname
FROM ggcompany a
WHERE a.companycode = SUBSTR(mm.companycode, 0, 4)) 二级机构,
(SELECT a.companycname
FROM ggcompany a
WHERE a.companycode = SUBSTR(mm.companycode, 0, 6)) 三级机构,
(SELECT a.companycname
FROM ggcompany a
WHERE a.companycode = mm.companycode) 四级机构,
mm.policyno 保单号
from gppolicyplandetail mm
方法2:使用WITH子句(CTE)
语法:
WITH count_cte AS (
SELECT column2, COUNT(*) AS count_value
FROM another_table
GROUP BY column2
)
SELECT
t1.column1,
count_cte.count_value
FROM
table1 t1
LEFT JOIN count_cte ON count_cte.column2 = t1.column1;
解释:count_cte 是中间表,命名随意,要是需要多个中间表,可以用逗号连接。
实例:
WITH
w AS (
SELECT
statdate ,
classname ,
riskname ,
cityname ,
policyno ,
registno ,
claimno ,
damagedate ,
reportdate ,
claimdate ,
underwriteenddate ,
endcasedate ,
rgstcncldate ,
canceldate ,
firstestloss ,
unsettledpaidbegin,
unsettledpaidend ,
settled ,
sumpaid ,
reportlossfee ,
canceldateloss
FROM
r_lsts_jsreportlist
WHERE
statdate = DATE '2022-03-31'
) ,
ff AS (
SELECT
statdate ,
classname ,
riskname ,
cityname ,
policyno ,
registno ,
claimno ,
damagedate ,
reportdate ,
claimdate ,
underwriteenddate ,
endcasedate ,
rgstcncldate ,
canceldate ,
firstestloss ,
unsettledpaidbegin,
unsettledpaidend ,
settled ,
sumpaid ,
reportlossfee ,
canceldateloss
FROM
r_lsts_jsreportlist
WHERE
statdate = DATE '2024-09-30'
)
SELECT
ff.statdate 统计日期,
ff.classname 险类 ,
ff.riskname 险种 ,
ff.cityname 机构 ,
w.settled
FROM
ff
LEFT JOIN w ON ff.riskname = w.riskname AND
ff.policyno = w.policyno AND
ff.registno = w.registno AND
ff.claimno = w.claimno
解释:W和FF都是临时表,中间用逗号隔开,中间结束需要有select ,select前不能有逗号。