Oracle SQL 到 return 来自唯一行的列值
Oracle SQL to return column values from unique rows
我有一个 table 具有多个子批次的单独批次:
+--------+----------+
¦Batch +Sub-batch ¦
¦--------¦----------¦
¦B_01 ¦SB_01 ¦
¦B_02 ¦SB_02 ¦
¦B_02 ¦SB_03 ¦
¦B_03 ¦SB_04 ¦
+--------+----------+
其中B_和SB_只是批次的名称(标识符),不需要聚合。
我愿意return:
+--------+-----------+-----------+
¦Batch +Sub_Batch1 ¦Sub_Batch2 ¦
¦--------¦-----------¦-----------¦
¦B_01 ¦SB_01 ¦ ¦
¦B_02 ¦SB_02 ¦SB_03 ¦
¦B_03 ¦SB_04 ¦ ¦
+--------+-----------+-----------+
看起来 PARTITION BY 或 PIVOT 是可行的方法,但我似乎只能找到聚合函数。
感谢收到任何帮助!
可以先应用row_number()
函数,再使用conditional aggregation
:
with t as
(
select t0.*,
row_number() over (partition by Batch order by Sub_batch) as rn
from t0
)
select Batch,
max(case when rn = 1 then Sub_batch end) as Sub_Batch1,
max(case when rn = 2 then Sub_batch end) as Sub_Batch2
from t
group by Batch
order by Batch;
如果只有 2 个 sub_batches 那么您可以简单地使用 MIN
和 MAX
聚合函数,如下所示:
SQL> WITH YOUR_TABLE(Batch, Sub_batch) AS
2 (SELECT 'B_01', 'SB_01' FROM DUAL UNION ALL
3 SELECT 'B_02', 'SB_02' FROM DUAL UNION ALL
4 SELECT 'B_02', 'SB_03' FROM DUAL UNION ALL
5 SELECT 'B_03', 'SB_04' FROM DUAL)
6 SELECT
7 BATCH,
8 MIN(SUB_BATCH) AS SUB_BATCH1,
9 CASE
10 WHEN MIN(SUB_BATCH) <> MAX(SUB_BATCH) THEN MAX(SUB_BATCH)
11 END AS SUB_BATCH2
12 FROM YOUR_TABLE
13 GROUP BY BATCH
14 ORDER BY BATCH;
BATCH SUB_BATCH1 SUB_BATCH2
---------- ---------- ----------
B_01 SB_01
B_02 SB_02 SB_03
B_03 SB_04
SQL>
干杯!!
我有一个 table 具有多个子批次的单独批次:
+--------+----------+
¦Batch +Sub-batch ¦
¦--------¦----------¦
¦B_01 ¦SB_01 ¦
¦B_02 ¦SB_02 ¦
¦B_02 ¦SB_03 ¦
¦B_03 ¦SB_04 ¦
+--------+----------+
其中B_和SB_只是批次的名称(标识符),不需要聚合。
我愿意return:
+--------+-----------+-----------+
¦Batch +Sub_Batch1 ¦Sub_Batch2 ¦
¦--------¦-----------¦-----------¦
¦B_01 ¦SB_01 ¦ ¦
¦B_02 ¦SB_02 ¦SB_03 ¦
¦B_03 ¦SB_04 ¦ ¦
+--------+-----------+-----------+
看起来 PARTITION BY 或 PIVOT 是可行的方法,但我似乎只能找到聚合函数。
感谢收到任何帮助!
可以先应用row_number()
函数,再使用conditional aggregation
:
with t as
(
select t0.*,
row_number() over (partition by Batch order by Sub_batch) as rn
from t0
)
select Batch,
max(case when rn = 1 then Sub_batch end) as Sub_Batch1,
max(case when rn = 2 then Sub_batch end) as Sub_Batch2
from t
group by Batch
order by Batch;
如果只有 2 个 sub_batches 那么您可以简单地使用 MIN
和 MAX
聚合函数,如下所示:
SQL> WITH YOUR_TABLE(Batch, Sub_batch) AS
2 (SELECT 'B_01', 'SB_01' FROM DUAL UNION ALL
3 SELECT 'B_02', 'SB_02' FROM DUAL UNION ALL
4 SELECT 'B_02', 'SB_03' FROM DUAL UNION ALL
5 SELECT 'B_03', 'SB_04' FROM DUAL)
6 SELECT
7 BATCH,
8 MIN(SUB_BATCH) AS SUB_BATCH1,
9 CASE
10 WHEN MIN(SUB_BATCH) <> MAX(SUB_BATCH) THEN MAX(SUB_BATCH)
11 END AS SUB_BATCH2
12 FROM YOUR_TABLE
13 GROUP BY BATCH
14 ORDER BY BATCH;
BATCH SUB_BATCH1 SUB_BATCH2
---------- ---------- ----------
B_01 SB_01
B_02 SB_02 SB_03
B_03 SB_04
SQL>
干杯!!