Pivoting

Business-Daten mit SQL analysieren

Michel Semaan

Data Scientist

Was ist Pivoting?

  • Pivoting: Eine Tabelle um eine Pivot-Spalte drehen; Werte einer Spalte zu Spalten transponieren
    • Wandelt eine „lange“ Tabelle in eine „breite“ um
Business-Daten mit SQL analysieren

Vorteile

  • Form der Tabelle steuern, Daten beibehalten
  • Horizontal entstapelte Daten sind oft leichter zu lesen als vertikal gestapelte
Business-Daten mit SQL analysieren

Vorher

meal_id  delivr_month  count_orders
-------  ------------  ------------
0        2018-06-01    39          
0        2018-07-01    47          
1        2018-06-01    25          
1        2018-07-01    55          

Nachher

meal_id  2018-06-01  2018-07-01
-------  ----------  ----------
0        39          47        
1        25          55        
  • Nach delivr_month gepivotet
Business-Daten mit SQL analysieren

Vorher-Tabelle

SELECT
  meal_id,
  DATE_TRUNC('month', order_date) :: DATE AS delivr_month,
  COUNT(DISTINCT orders) :: INT AS revenue
FROM meals
JOIN orders ON meals.meal_id = orders.meal_id
WHERE meals.meal_id IN (0, 1)
  AND order_date < '2018-08-01'
GROUP BY meal_id, delivr_month
ORDER BY meal_id, delivr_month;
Business-Daten mit SQL analysieren

CROSSTAB()

CREATE EXTENSION IF NOT EXISTS tablefunc;
  • CREATE EXTENSION ist wie import in Python
SELECT * FROM CROSSTAB($$
  TEXT source_sql
$$)

AS ct (column_1 DATA_TYPE_1,
       column_2 DATA_TYPE_2,
       ...,
       column_n DATA_TYPE_N)
;
Business-Daten mit SQL analysieren

CROSSTAB() verwenden

CREATE EXTENSION IF NOT EXISTS tablefunc;

SELECT * FROM CROSSTAB($$ SELECT meal_id, DATE_TRUNC('month', order_date) :: DATE AS delivr_month, COUNT(DISTINCT order_id) :: INT AS orders FROM orders WHERE meal_id IN (0, 1) AND order_date < '2018-08-01' GROUP BY meal_id, delivr_month ORDER BY meal_id, delivr_month $$)
AS ct (meal_id INT, "2018-06-01" INT, "2018-07-01" INT) ORDER BY meal_id ASC;
Business-Daten mit SQL analysieren

Vorher-Tabelle

meal_id  delivr_month  count_orders
-------  ------------  ------------
0        2018-06-01    39          
0        2018-07-01    47          
1        2018-06-01    25          
1        2018-07-01    55          

Nachher-Tabelle

meal_id  2018-06-01  2018-07-01
-------  ----------  ----------
0        39          47        
1        25          55        
  • Nach delivr_month gepivotet
Business-Daten mit SQL analysieren

Pivoting

Business-Daten mit SQL analysieren

Preparing Video For Download...