从两个不同的select语句中保存两个值的最佳和简单方法是什么?
我的查询是这样的:
SELECT * FROM (
SELECT FIELD1 FROM (<SUB SELECT STATMENT>)
UNION ALL
SELECT FIELD2 FROM (<SUB SELECT STATMENT>))
我想要的是保存FIELD1和FIELD2的值,以便稍后我可以用它做一些计算,比如FIELD1 / FIELD2。我尝试使用游标但遇到了问题。对于select语句来说太复杂了。有什么建议吗?
更新:
我当前查询的结果集如下所示。
SUM_OF_MESSAGES | LABEL
----------------------------
145323 | PUSHED
2633267 | RECEIVED
|
我想从前两行中取出值并将它们分开。例如。 145323/2633267
换句话说,有没有办法将FIELD1除以上面的查询中的FIELD2?
另一个更新:
这是我的问题:
SELECT SUM(R.MESSAGES) AS SUM_OF_MESSAGES, CASE WHEN R.LABEL = 1 THEN 'PUSHED' WHEN R.LABEL = 2 THEN 'RECEIVED' END AS LABEL FROM (
SELECT SUM(Q.MESSAGES) AS "MESSAGES", 1 LABEL FROM (
SELECT USER_LOGIN,
EVENT_MSG,
ROW_LST_UPD_TS,
COMPONENT_NAME,
REGEXP_SUBSTR (SUBSTR (EVENT_MSG, INSTR (EVENT_MSG, ' ', 1, 1), INSTR (EVENT_MSG, ' ', 1, 1)), '[0-9]+') AS "MESSAGES"
FROM EVENT_MGT.EVENT_LOG
WHERE ROW_LST_UPD_TS BETWEEN (TRUNC (:DATEINPUT) - 1) + 5 / 86400 AND (TRUNC (:DATEINPUT)) + 5 / 86400
AND EVENT_ID = 101
AND COMPONENT_NAME LIKE '%Web ICE Downloader.exe%'
GROUP BY COMPONENT_NAME,
USER_LOGIN,
EVENT_MSG,
ROW_LST_UPD_TS
ORDER BY ROW_LST_UPD_TS ) Q
UNION ALL
SELECT SUM(Q.MESSAGES) "MESSAGES", 2 LABEL FROM (
SELECT USER_LOGIN,
EVENT_MSG,
ROW_LST_UPD_TS,
COMPONENT_NAME,
REGEXP_SUBSTR (SUBSTR (EVENT_MSG, INSTR (EVENT_MSG, ' ', 1, 1), INSTR (EVENT_MSG, ' ', 1, 1)), '[0-9]+') AS "MESSAGES"
FROM EVENT_MGT.EVENT_LOG
WHERE ROW_LST_UPD_TS BETWEEN (TRUNC (:DATEINPUT) - 1) + 5 / 86400 AND (TRUNC (:DATEINPUT)) + 5 / 86400
AND EVENT_ID = 100
AND COMPONENT_NAME LIKE '%Web ICE Downloader.exe%'
GROUP BY COMPONENT_NAME,
USER_LOGIN,
EVENT_MSG,
ROW_LST_UPD_TS
ORDER BY ROW_LST_UPD_TS ) Q ) R
GROUP BY R.LABEL
这是我的结果集:
SUM_OF_MESSAGES | LABEL
----------------------------
145323 | PUSHED
2633267 | RECEIVED
|
我想在同一个select语句中将这两个数字分开。请帮忙。
答案 0 :(得分:1)
您的聚合似乎只需要一个带有一点逻辑的查询
SELECT COUNT( CASE WHEN event_id = 100
THEN q.messages
ELSE null
END) Received,
COUNT( CASE WHEN event_id = 101
THEN q.messages
ELSE null
END) Pushed,
COUNT( CASE WHEN event_id = 101
THEN q.messages
ELSE null
END) /
COUNT( CASE WHEN event_id = 100
THEN q.messages
ELSE null
END) Pushed_Over_Received
FROM (
SELECT USER_LOGIN,
EVENT_ID,
EVENT_MSG,
ROW_LST_UPD_TS,
COMPONENT_NAME,
REGEXP_SUBSTR (SUBSTR (EVENT_MSG, INSTR (EVENT_MSG, ' ', 1, 1),
INSTR (EVENT_MSG, ' ', 1, 1)), '[0-9]+') AS "MESSAGES"
FROM EVENT_MGT.EVENT_LOG
WHERE ROW_LST_UPD_TS BETWEEN (TRUNC (:DATEINPUT) - 1) + 5 / 86400
AND (TRUNC (:DATEINPUT)) + 5 / 86400
AND EVENT_ID in( 100, 101 )
AND COMPONENT_NAME LIKE '%Web ICE Downloader.exe%'
)
或者,您可以使用分析函数执行类似的操作(您希望将查询中的子查询t
替换为您编写的产生两行输出的查询。
SQL> ed
Wrote file afiedt.buf
1 with t as (
2 select 145323 sum_of_messages, 'PUSHED' label from dual
3 union all
4 select 2633267, 'RECEIVED' from dual
5 )
6 select sum_of_messages,
7 label,
8 round( 100*ratio_to_report(sum_of_messages) over (), 2) pct_of_messages
9* from t
SQL> /
SUM_OF_MESSAGES LABEL PCT_OF_MESSAGES
--------------- -------- ---------------
145323 PUSHED 5.23
2633267 RECEIVED 94.77