我需要您的帮助来创建用于更新表中字段的脚本。
在我的应用程序中,我有创建表REQUESTS(表REQUEST)的人(表PERSON)。 在过去3年中创建请求的人是活跃的。 我已经在表PERSON中创建了一个字段(ACTIVE-默认值:1),以了解此人是否仍在活动。
我创建一个查询以检索每个人的请求数(活动请求,非活动请求):
select p.ID, p.LASTNAME || ' ' || p.FIRSTNAME personName,p.COMPANY, p.ACTIVE,
(SELECT COUNT(*) FROM request req WHERE req.PERSONID = p.ID) AS "NB_REQUEST",
(SELECT COUNT(*) FROM request reqAct WHERE reqAct.PERSONID = p.ID and reqAct.requestdate > ADD_MONTHS(TRUNC(SYSDATE, 'YYYY'), -36)) AS "NB_ACTIVE_REQUESTS",
(SELECT COUNT(*) FROM request reqInact WHERE reqInact.PERSONID = p.ID and reqInact.requestdate < ADD_MONTHS(TRUNC(SYSDATE, 'YYYY'), -36)) AS "NB_INACTIVE_REQUESTS"
from person p
此脚本正在运行。现在,我想实现一个脚本,用于在人员处于活动状态时更新“活动”字段。我第一次尝试实施IF语句,但是它不起作用。
select p.ID, p.LASTNAME || ' ' || p.FIRSTNAME personName,p.COMPANY, p.ACTIVE,
(SELECT COUNT(*) FROM request req WHERE req.PERSONID = p.ID) AS "NB_REQUEST",
(SELECT COUNT(*) FROM request reqAct WHERE reqAct.PERSONID = p.ID and reqAct.requestdate > ADD_MONTHS(TRUNC(SYSDATE, 'YYYY'), -36)) AS "NB_ACTIVE_REQUESTS",
(SELECT COUNT(*) FROM request reqInact WHERE reqInact.PERSONID = p.ID and reqInact.requestdate < ADD_MONTHS(TRUNC(SYSDATE, 'YYYY'), -36)) AS "NB_INACTIVE_REQUESTS"
(IF((SELECT COUNT(*) FROM request reqReAct WHERE reqAct.PERSONID = p.ID and reqReAct.requestdate > ADD_MONTHS(TRUNC(SYSDATE, 'YYYY'), -36))) > 0 THEN 1 ELSE 0) AS "RE-ACTIVE"
from person p
您能帮我做到吗?
感谢您的帮助
答案 0 :(得分:1)
您可以使用CASE ... END
表达式。您可能还想尝试使用EXISTS
而不是计数。那可能更快。
SELECT p.id,
p.lastname || ' ' || p.firstname personname,
p.company,
p.active,
(SELECT count(*)
FROM request req
WHERE req.personid = p.id) nb_request,
(SELECT count(*)
FROM request reqact
WHERE reqact.personid = p.id
AND reqact.requestdate > add_months(trunc(sysdate, 'YYYY'), -36)) nb_active_requests,
(SELECT count(*)
FROM request reqinact
WHERE reqinact.personid = p.id
AND reqinact.requestdate < add_months(trunc(sysdate, 'YYYY'), -36)) nb_inactive_requests,
CASE
WHEN EXISTS (SELECT *
FROM request reqreact
WHERE reqact.personid = p.id
AND reqreact.requestdate > add_months(trunc(sysdate, 'YYYY'), -36)) THEN
1
ELSE
0
END re_active
FROM person p;
另一种选择是Oracle专有的decode()
。
顺便说一句:在比较两个requestdate
子查询时,仅使用了<
和>
运算符。这为=
情况留下了空白。也许这不是故意的,您想检查是否对其中之一使用=<
或=<
。
答案 1 :(得分:0)
那么只需将if语句替换为大小写条件
select p.ID,
p.LASTNAME || ' ' || p.FIRSTNAME personName,
p.COMPANY,
p.ACTIVE,
(SELECT COUNT(*) FROM request req WHERE req.PERSONID = p.ID) AS "NB_REQUEST",
(SELECT COUNT(*)
FROM request reqAct
WHERE reqAct.PERSONID = p.ID
and reqAct.requestdate > ADD_MONTHS(TRUNC(SYSDATE, 'YYYY'), -36)) AS "NB_ACTIVE_REQUESTS",
(SELECT COUNT(*)
FROM request reqInact
WHERE reqInact.PERSONID = p.ID
and reqInact.requestdate <
ADD_MONTHS(TRUNC(SYSDATE, 'YYYY'), -36)) AS "NB_INACTIVE_REQUESTS",
case when ( SELECT COUNT(*)
FROM request reqReAct
WHERE reqAct.PERSONID = p.ID
and reqReAct.requestdate >
ADD_MONTHS(TRUNC(SYSDATE,
'YYYY'),
-36))) >0 THEN 1 ELSE 0 end ) AS "RE-ACTIVE"
from person p