簡體   English   中英

如何在 SQL / Snowflake 中創建列和行相同的交叉表/系數表?

[英]How to create a crosstab / coefficient table where columns and rows are the same in SQL / Snowflake?

我有一張像

      col1 | col2 | col3 | col4 | col5
 id1 |  1     0      0      1      0
 id2 |  1     1      0      0      0
 id3 |  0     1      0      1      0
 id4 |  0     0      1      0      1
 id5 |  1     0      1      0      0
 id6 |  0     0      0      1      0
  .
  .
  .
 idN

我將如何創建一個查詢,以便我得到一個類似的表

      col1 | col2 | col3 | col4 | col5
col1 |  3     1      1      1      0
col2 |  1     2      0      1      0
col3 |  1     1      2      0      1
col4 |  1     1      1      2      0
col5 |  0     0      1      0      1

其中結果中的每個條目是一個列中的某個值 1 與另一個值為 1 的列一起出現的次數。

我可以通過執行以下操作獲得對角線值:

SELECT 
sum(col1), sum(col2), sum(col3), sum(col4), sum(col5)
FROM (
SELECT 
col1, col2, col3, col4, col5, col1 + col2 + col3 + col4 + col5 ) AS total
FROM (
SELECT 
      ROW_NUMBER()OVER(PARTITION BY id ORDER BY date) row_num, *
FROM (
SELECT DISTINCT(id), date, col1, col2, col3, col4, col5
FROM db.schema.table)
)
WHERE row_num = 1 AND total <= 1
ORDER BY total DESC);

我假設我必須做某種 pivot 或各種聯合,但我似乎無法弄清楚。

您可以使用 5 個選擇和 25 個案例語句的聯合來解決它 - 每個 select 中有 5 個案例語句。 我不得不承認這是一個非常丑陋的解決方案,並且只有當你有恆定數量的列時才會起作用,但它肯定會完成這項工作。

由於您不知道確切的列數,因此想法 ios 取消旋轉冷杉,操作它們並返回 pivot。 這應該有效:

-- identify table columns
with table_columns_list as (
select column_name, ordinal_position
from information_schema.columns
where table_schema like 'schema' and table_name like 'table' 
   ),
-- unpivot the table and add row id 
flat_table as (
select * from ( select * , row_number() as row_id from my_table)
unpivot(value for column_name in (select column_name from table_columns_list)
),
-- calculate all matrix values
full_flat_table as ( 
select a.row_id as row_id , a.column_name as a_column_name, b.column_name as 
b_column_name, min(a.value,b.value) as value
from flat_table as a inner join  flat_table as b on a.row_id=b.row_id
)

select * 
from full_flat_table
pivot(sum(value) for a_column_name in (select column_name from 
table_columns_list))
as p
order by b_column_name; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM