我在oracle中有这些数据集:
app_name batch_group session_total
-------- ------------ -------------
app1 b1 5
app2 b1 10
app1 b2 80
app2 b2 99
app1 b3 20
app2 b3 59
我想在oracle
中提供这些格式的数据app_name session1 session2 session3
-------- -------- -------- --------
app1 5 80 20
app2 10 99 59
会话将根据批量增加。如果得到6批将在会议6之前出来。请帮助我,因为我在sql中新建了
答案 0 :(得分:1)
Oracle 11g R2架构设置:
CREATE TABLE TEST ( app_name, batch_group, session_total ) AS
SELECT 'app1', 'b1', 5 FROM DUAL
UNION ALL SELECT 'app2', 'b1', 10 FROM DUAL
UNION ALL SELECT 'app1', 'b2', 80 FROM DUAL
UNION ALL SELECT 'app2', 'b2', 99 FROM DUAL
UNION ALL SELECT 'app1', 'b3', 20 FROM DUAL
UNION ALL SELECT 'app2', 'b3', 59 FROM DUAL;
查询1 :
SELECT app_name,
SUM( CASE batch_group WHEN 'b1' THEN session_total END ) AS session1,
SUM( CASE batch_group WHEN 'b2' THEN session_total END ) AS session2,
SUM( CASE batch_group WHEN 'b3' THEN session_total END ) AS session3
FROM TEST
GROUP BY app_name
<强> Results 强>:
| APP_NAME | SESSION1 | SESSION2 | SESSION3 |
|----------|----------|----------|----------|
| app1 | 5 | 80 | 20 |
| app2 | 10 | 99 | 59 |
查询2 :
SELECT * FROM
(
SELECT *
FROM TEST
)
PIVOT
(
SUM( session_total)
FOR batch_group
IN (
'b1' AS session1,
'b2' AS session2,
'b3' AS session3
)
)
<强> Results 强>:
| APP_NAME | SESSION1 | SESSION2 | SESSION3 |
|----------|----------|----------|----------|
| app1 | 5 | 80 | 20 |
| app2 | 10 | 99 | 59 |