Oracle

Oracle SQL - 如何按列分組並為每個不同的值計算其他列?

  • April 9, 2021

在查詢 2 個表時,我正在努力嘗試獲得所需的結果。這些是表格:

表格1

表2

我在這裡要完成的是創建一個按table2-column2分組的視圖,並為分組列的每一行計算abcd ( table1-column2中的每個不同數據)的出現;像這樣的東西:

所需視圖

表之間存在one2many關係:table1可以有多個具有相同外鍵的條目;因此table1-column2可以有多個重複條目用於列中的相同數據,如圖所示。table1-column2中所有不同的值都是已知值,所以可以使用where子句。

我很難為分組列中的特定條目計算table1-column2中每個不同數據的出現次數(我正在為 table2 中的每種類型的數據獲取 table1 中的全部條目數量**-**第 2 列)。

我還嘗試為table2-column2中的每種類型的已知數據創建選擇,但我不知道在這種情況下如何只返回一行,因此觸發了錯誤單行子查詢返回多行。

任何建議都非常感謝。謝謝。

看起來你想要這樣的東西

with t1 as (
 select 2 c1, 'a' c2 from dual union all
 select 2, 'a' from dual union all
 select 3, 'c' from dual union all
 select 4, 'a' from dual union all
 select 4, 'b' from dual union all
 select 4, 'b' from dual union all
 select 4, 'd' from dual
),
t2 as (
 select 1 c1, '01' c2 from dual union all
 select 2, '02' from dual union all
 select 3, '03' from dual union all
 select 4, '04' from dual)
select t2.c2,
      sum( case when t1.c2 = 'a' then 1 else 0 end) count_a,
      sum( case when t1.c2 = 'b' then 1 else 0 end) count_b,
      sum( case when t1.c2 = 'c' then 1 else 0 end) count_c,
      sum( case when t1.c2 = 'd' then 1 else 0 end) count_d
 from t2
      left outer join t1 on (t1.c1 = t2.c2)
group by t2.c2
order by t2.c2

引用自:https://dba.stackexchange.com/questions/289566