Power Query for Analysts: Difference between revisions

From Training Material
Jump to navigation Jump to search
Gpruszczynski (talk | contribs)
No edit summary
 
(47 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{Cat|Power Query|001}}
{{Cat|Power Query|001}}
== Modul 1: Wprowadzenie do Power Query i podstawowe transformacje ==
== Module 1: Introduction to Power Query and Basic Transformations ==


=== Cel ===
=== Objective ===
W tym ćwiczeniu nauczysz się:
In this exercise, you will learn to:


Importować dane z pliku CSV do Power Query.
* Import data from a CSV file into Power Query.
Sprawdzać i dostosowywać typy danych, koncentrując się na konwersji daty zapisanej jako tekst na rzeczywisty typ daty.
* Review and adjust data types, focusing on converting a date stored as text into a proper date type.
Zastosować podstawowe filtrowanie danych.
* Apply basic data filtering.
Korzystać z pomocy zewnętrznej (np. ChatGPT) w celu uzyskania wskazówek dotyczących tworzenia niestandardowego kodu M, bez bezpośredniego kopiowania rozwiązań.
* Use external help (e.g., ChatGPT) to get guidance on creating custom M code, without directly copying solutions.
=== Dostarczone dane ===
Otrzymujesz do pobrania plik CSV o nazwie
📂[[Media:PQsales.csv]]
który zawiera dane zamówień sprzedaży.


=== Instrukcje ===
=== Files Provided ===
You can download the CSV file 
📂[[Media:PQsales.csv]] 
which contains sales order data.


* Krok 1: Importuj dane
=== Instructions ===


#Otwórz Power Query w Excelu lub Power BI.
* Step 1: Import the data
#Zaimportuj dane z pliku sales.csv.
#Zauważ, że kolumna OrderDate została zaimportowana jako tekst ze względu na swój format (dd/MM/yyyy).
* Krok 2: Sprawdź i przekonwertuj typy danych


#Sprawdź, czy każda kolumna ma poprawny typ danych.
# Open Power Query in Excel or Power BI.
#Ręcznie przekształć kolumnę OrderDate z tekstu na typ daty.
# Import the data from the file sales.csv.
#Wskazówka: Jeśli napotkasz trudności, możesz zapytać ChatGPT o wskazówki, jak napisać funkcję M do konwersji tekstu na datę.
# Note that the *OrderDate* column was imported as text due to its format (dd/MM/yyyy).
* Krok 3: Zastosuj podstawowe filtrowanie


#Filtruj zestaw danych, tak aby pozostały tylko wiersze, w których koszt jest większy niż 200.
* Step 2: Check and convert data types
#Propozycja: Użyj interfejsu graficznego Power Query lub napisz prosty skrypt M, aby zastosować filtr. Jeśli to konieczne, skonsultuj się z ChatGPT w celu uzyskania pomysłów na implementację tego filtru.
* Krok 4: Przejrzyj i zapisz swoją pracę


#Potwierdź, że transformacje zostały poprawnie zastosowane, przeglądając podgląd danych.
# Verify that each column has the correct data type.
#Zapisz zapytanie i udokumentuj kroki, które podjąłeś.
# Manually transform the *OrderDate* column from text to date type.
# Tip: If you encounter difficulties, you can ask ChatGPT for hints on how to write an M function to convert text to date.


=== Zadanie ===
* Step 3: Apply basic filtering


Wykonaj kroki opisane powyżej w Power Query.
# Filter the dataset to keep only rows where the cost is greater than 200.
Eksperymentuj z dostępnymi opcjami transformacji i staraj się zrozumieć, jak każdy krok wpływa na Twoje dane.
# Suggestion: Use Power Query’s graphical interface or write a simple M script to apply the filter. If needed, consult ChatGPT for implementation ideas.
Używaj ChatGPT w celu uzyskania wskazówek lub rozwiązywania problemów, ale unikaj kopiowania kompletnych rozwiązań dosłownie.


== Modul 2: Laczenie i scalanie danych z wielu zrodel ==
* Step 4: Review and save your work


=== Cel ===
# Confirm that the transformations were applied correctly by reviewing the data preview.
# Save the query and document the steps you have taken.


W tym ćwiczeniu nauczysz się:
=== Task ===


Importować dane z wielu plików CSV do Power Query. Scalić (połączyć) dane z różnych źródeł na podstawie wspólnego klucza. Użyć lewego zewnętrznego łączenia (Left Outer Join) do dodania szczegółów klienta do zamówień sprzedaży. Korzystać z pomocy zewnętrznej (np. ChatGPT) w celu uzyskania wskazówek dotyczących pisania niestandardowego kodu M, bez kopiowania kompletnych rozwiązań.
Perform the steps described above in Power Query.
=== Dostarczone dane ===
Experiment with available transformation options and try to understand how each step affects your data.
Otrzymujesz do pobrania dwa pliki CSV:
Use ChatGPT for hints or troubleshooting, but avoid copying complete solutions verbatim.


📂 [[Media:PQ_sales2.csv]] – Zawiera dane zamówień sprzedaży:
== Module 2: Combining and Merging Data from Multiple Sources ==


📂 [[Media:PQ_customers.csv]] – Zawiera informacje o klientach:
=== Objective ===


=== Instrukcje ===
In this exercise, you will learn to:


*Krok 1: Importuj dane
* Import data from multiple CSV files into Power Query.
Otwórz Power Query w Excelu lub Power BI. Zaimportuj dane z obu plików PQ_sales.csv i PQ_customers.csv. Sprawdź, czy oba zapytania zostały załadowane poprawnie.
* Merge data from different sources based on a common key.
* Use a Left Outer Join to add customer details to sales orders.
* Use external help (e.g., ChatGPT) to get guidance on writing custom M code, without copying complete solutions.


*Krok 2: Sprawdź i przekonwertuj typy danych
=== Files Provided ===
Potwierdź, że każda kolumna ma odpowiedni typ danych w obu zapytaniach. Na przykład, zauważ, że kolumna OrderDate w PQ_sales.csv jest zaimportowana jako tekst z powodu niestandardowego formatu. Wskazówka: Użyj funkcji transformacji, jeśli jakiekolwiek dostosowania są potrzebne.
You can download the following two CSV files:


*Krok 3: Scal dane
📂 [[Media:PQ_sales2.csv]] – Contains sales order data 
Scal zapytanie PQ_sales.csv z zapytaniem PQ_customers.csv. Użyj kolumny Customer jako klucza dopasowania. Wybierz lewy zewnętrzny join (Left Outer Join), aby każde zamówienie sprzedaży zostało zachowane wraz z odpowiednimi szczegółami klienta. Propozycja: Jeśli nie wiesz, jak napisać kod M do tego scalenia, zapytaj ChatGPT o wskazówki dotyczące scalania zapytań.


*Krok 4: Przejrzyj scalone dane
📂 [[Media:PQ_customers.csv]] – Contains customer information
Potwierdź, że wynikowe zapytanie zawiera dodatkowe kolumny (np. Region, CustomerSince) z pliku PQ_customers.csv. Sprawdź scalone dane, aby upewnić się, że szczegóły klientów zostały poprawnie połączone z odpowiednimi zamówieniami sprzedaży.


*Krok 5: Zapisz swoją pracę
=== Instructions ===
Zapisz swoje zapytanie i udokumentuj kroki transformacji, które zastosowałeś.


=== Zadanie ===
* Step 1: Import the data 
Open Power Query in Excel or Power BI. 
Import data from both files: PQ_sales.csv and PQ_customers.csv. 
Check that both queries have been loaded correctly.


Wykonaj kroki opisane powyżej w Power Query. Eksperymentuj z interfejsem graficznym i niestandardowym kodem M w celu wykonania scalania. Korzystaj z zasobów zewnętrznych (np. ChatGPT) w celu uzyskania wskazówek lub rozwiązywania problemów, ale unikaj kopiowania kompletnych rozwiązań dosłownie.
* Step 2: Check and convert data types 
Ensure that each column has the correct data type in both queries.
For example, note that the *OrderDate* column in PQ_sales.csv may be imported as text due to a non-standard format.
Tip: Use the transformation functions if any adjustments are needed.


== Modul 3: Tworzenie niestandardowych kolumn i funkcji ==
* Step 3: Merge the data 
Merge the *PQ_sales.csv* query with the *PQ_customers.csv* query. 
Use the *Customer* column as the matching key. 
Choose the Left Outer Join option so that every sales order is retained along with the corresponding customer details. 
Suggestion: If you’re not sure how to write M code for this merge, ask ChatGPT for tips on how to merge queries.


=== Cel ===
* Step 4: Review the merged data 
W tym ćwiczeniu nauczysz się:
Confirm that the resulting query includes additional columns (e.g., *Region*, *CustomerSince*) from the PQ_customers.csv file. 
Check the merged data to ensure that customer details have been correctly linked to the corresponding sales orders.


Tworzyć niestandardowe kolumny obliczeniowe w Power Query.
* Step 5: Save your work 
Save your query and document the transformation steps you applied.


Używać wbudowanych funkcji Power Query do manipulacji tekstem, liczbami i datami.
=== Task ===


Pisać niestandardowe funkcje w języku M, aby automatyzować transformacje.
Perform the steps described above in Power Query. 
Experiment with both the graphical interface and custom M code to complete the merge. 
Use external resources (e.g., ChatGPT) for guidance or troubleshooting, but avoid copying complete solutions verbatim.


Korzystać z ChatGPT do pomocy przy pisaniu i optymalizacji kodu M.
== Module 3: Creating Custom Columns and Functions ==


=== Dostarczone dane ===
=== Objective ===  
In this exercise, you will learn to:


Do tego ćwiczenia wykorzystamy następujące zbiory danych:
* Create custom calculated columns in Power Query.
* Use built-in Power Query functions to manipulate text, numbers, and dates.
* Write custom M functions to automate transformations.
* Use ChatGPT to assist in writing and optimizing M code.


📂[[Media:PQ_sales2.csv]] (używany w poprzednich modułach)
=== Files Provided ===


📂[[Media:PQ_discounts.csv]] (nowy zbiór danych) - zawiera stawki rabatowe w zależności od typu produktu.
The following datasets are used for this exercise:


=== Instrukcje ===
📂[[Media:PQ_sales2.csv]] (used in previous modules) 
📂[[Media:PQ_discounts.csv]] (new dataset) – contains discount rates based on product type.


*Krok 1: Importuj dane
=== Instructions ===
Otwórz Power Query w Excelu lub Power BI.
Zaimportuj oba pliki: PQ_sales.csv i PQ_discounts.csv.
Upewnij się, że obie tabele zostały załadowane poprawnie.


* Step 1: Import the data 
Open Power Query in Excel or Power BI. 
Import both files: *PQ_sales.csv* and *PQ_discounts.csv*. 
Ensure both tables are loaded correctly.


<br>
<br>
*Krok 2: Tworzenie niestandardowej kolumny dla całkowitego kosztu
* Step 2: Create a custom column for total cost 
W tabeli PQ_sales dodaj nową niestandardową kolumnę:
In the *PQ_sales* table, add a new custom column:
Przejdź do Dodaj kolumnę Kolumna niestandardowa.
Go to **Add Column Custom Column**.
Nazwij ją TotalCost.
Name it `TotalCost`.
Utwórz formułę do obliczenia całkowitego kosztu jako:
Create a formula to calculate the total cost as:
  Quantity * Cost
  `Quantity * Cost
Click OK and review the results.


Kliknij OK i sprawdź wyniki.
<br>
* Step 3: Apply discounts using merge 
Merge *PQ_sales* with *PQ_discounts* using the *Product* column as the key. 
Expand the `DiscountRate` column into the *PQ_sales* table. 
Add another custom column named `DiscountedPrice`: 
`[TotalCost] - ([TotalCost] * [DiscountRate])` 
Check that the new column correctly applies the discounts.


<br>
* Step 4: Create a custom function in M 
Create a function to categorize products into price bands: 
Go to **Home → Advanced Editor**. 
Write an M function that takes `Cost` as input and returns a category: 
Low if Cost < 500  Medium if Cost between 500 and 1500  High if Cost > 1500 


<br>
*Krok 3: Zastosowanie rabatów za pomocą scalania
Scal PQ_sales z PQ_discounts, używając kolumny Product jako klucza.
Rozwiń kolumnę DiscountRate do tabeli PQ_sales.
Dodaj kolejną niestandardową kolumnę o nazwie DiscountedPrice:
[TotalCost] - ([TotalCost] * [DiscountRate])


Sprawdź, czy nowa kolumna poprawnie stosuje rabaty.
<br>
<br>
*Krok 4: Tworzenie niestandardowej funkcji w M
* Step 5: Assign categories 
Utwórz funkcję do kategoryzowania produktów w różne przedziały cenowe:
In the *PQ_sales* table, add a custom column using the function. 
Przejdź do Strona główna → Edytor zaawansowany.
Name the column `PriceCategory`.
Napisz funkcję M, która przyjmuje Cost jako wejście i zwraca kategorię:
Make sure the categories display correctly based on the values in the *Cost* column.
Low if Cost < 500 Medium if Cost between 500 and 1500 High if Cost > 1500


Wskazówka: Jeśli nie jesteś pewny, jak zbudować funkcję, zapytaj ChatGPT: "Jak napisać funkcję M, która kategoryzuje ceny na Low, Medium i High?" <br>
=== Task ===
* ✔ Complete all steps in Power Query. 
* ✔ Experiment with both the graphical interface and M code. 
* ✔ Use ChatGPT for troubleshooting or refining your M scripts.


*Krok 5: Przypisywanie kategorii
== Module 4: Advanced Data Transformations in Power Query ==
W tabeli PQ_sales dodaj niestandardową kolumnę, używając funkcji.
Nazwij kolumnę PriceCategory.
Upewnij się, że kategorie są wyświetlane poprawnie na podstawie wartości w kolumnie Cost.


=== Zadanie ===  
=== Objective ===  
*✔ Wykonaj wszystkie kroki w Power Query.
In this module, you will learn: 
*✔ Eksperymentuj zarówno z interfejsem graficznym, jak i z kodem M.
* ✔ How to pivot and unpivot data in Power Query
*✔ Korzystaj z ChatGPT w celu rozwiązywania problemów lub poprawiania skryptu M.
* ✔ How to split and merge columns for better data structure 
* ✔ How to use conditional transformations 
* ✔ How to leverage ChatGPT to build complex M scripts


== Modul 4: Zaawansowane transformacje danych w Power Query ==
=== Files Provided ===


=== Cel ===
This exercise introduces a new dataset: 
W tym module nauczysz się:  
'''📂 [[Media:PQ_sales_pivot.csv]]''' – contains monthly sales data in a pivoted format.
*✔ Jak pivotować i unpivotować dane w Power Query.
*✔ Jak dzielić i scalać kolumny w celu lepszej strukturyzacji danych.  
*✔ Jak używać transformacji warunkowych.
*✔ Jak wykorzystać ChatGPT do tworzenia złożonych skryptów M.


=== Dostarczone dane ===
=== Instructions ===


Do tego ćwiczenia wprowadzimy nowy zbiór danych:
'''Step 1: Import the data''' 
  PQ_sales_pivot.csv, który zawiera miesięczne dane sprzedaży różnych produktów.
Open Power Query in Excel or Power BI.  
Import the file *PQ_sales_pivot.csv*. 
Ensure the table loads correctly.


'''📂 [[Media:PQ_sales_pivot.csv]]''' - Struktura danych w formacie pivot.
<br>
'''Step 2: Unpivot the data'''
The current table has a wide format that is not ideal for analysis.
Unpivot the monthly columns so the data structure becomes:


=== Instrukcje ===
* Product 
* Category 
* Month 
* Sales Amount


Krok 1: Importuj dane
How to do it:
Otwórz Power Query w Excelu lub Power BI.
Zaimportuj plik PQ_sales_pivot.csv.
Upewnij się, że tabela została poprawnie załadowana.
<br>
Krok 2: Unpivotowanie danych
Obecna tabela ma szeroki format, który nie jest idealny do analizy.
Unpivotuj kolumny miesięczne, aby dane miały strukturę:
*Product
*Category
*Month
*Sales Amount
<br>


Jak to zrobić:
# Click **Transform → Use First Row as Headers** to make sure column names are correct.
# Select the month columns (e.g., Jan 2025, Feb 2025, etc.).
# Click **Transform → Unpivot Columns**.
# Rename the resulting columns:
## Attribute → Month
## Value → Sales Amount


#Kliknij Transformuj → Użyj pierwszego wiersza jako nagłówków, aby upewnić się, że kolumny mają poprawne nazwy.
#Zaznacz kolumny z miesiącami (Jan 2025, Feb 2025 itd.).
#Kliknij Transformuj → Unpivotuj kolumny.
#Zmień nazwy wynikowych kolumn:
"Attribute" → Month
"Value" → Sales Amount
<br>
<br>
Krok 3: Dzielnie i scalanie kolumn
'''Step 3: Splitting and merging columns'''
#Kolumna Month obecnie zawiera wartości takie jak "Jan 2025".
#Podziel tę kolumnę na Month Name i Year:
#Zaznacz kolumnę Month.
#Kliknij Transformuj → Podziel kolumnę → Według ogranicznika.
#Wybierz spację (" ") jako ogranicznik.
#Zmień nazwy nowych kolumn na Month Name i Year.
*Przykład scalania kolumn:


Jeśli chcesz scalić Product i Category, zaznacz obie kolumny.
# The `Month` column now contains values like "Jan 2025".
# Split this column into `Month Name` and `Year`: 
# Select the `Month` column. 
# Click **Transform → Split Column → By Delimiter**. 
# Choose space (" ") as the delimiter. 
# Rename the new columns to `Month Name` and `Year`.
 
*Example of merging columns:* 
To merge `Product` and `Category`, select both columns: 
# Click **Transform → Merge Columns**. 
# Use `" - "` as the separator (e.g., `"Monitor - Electronics"`).


#Kliknij Transformuj → Scal kolumny.
#Użyj " - " jako separatora (np. "Monitor - Electronics").
<br>
<br>
Krok 4: Dodanie transformacji warunkowych
'''Step 4: Adding conditional transformations''' 
*Dodaj nową niestandardową kolumnę o nazwie "Sales Performance":
Add a new custom column named `Sales Performance` with the following logic:


  if [Sales Amount] < 300 then "Low" else if [Sales Amount] >= 300 and [Sales Amount] < 800 then "Medium" else "High"
  if [Sales Amount] < 300 then "Low"
else if [Sales Amount] >= 300 and [Sales Amount] < 800 then "Medium"
else "High"


*Upewnij się, że kolumna poprawnie kategoryzuje wyniki sprzedaży.


=== Zadanie ===
Make sure the column correctly categorizes the sales performance.
*✔ Wykonaj wszystkie kroki w Power Query.
*✔ Eksperymentuj z unpivotowaniem, dzieleniem, scalaniem i logiką warunkową.
*✔ Korzystaj z ChatGPT w celu rozwiązywania problemów lub poprawiania skryptu M.


== Modul 5: Parametryzacja i dynamiczne zapytania w Power Query ==
=== Task ===
* ✔ Complete all steps in Power Query
* ✔ Experiment with unpivoting, splitting, merging, and conditional logic 
* ✔ Use ChatGPT for troubleshooting or refining your M scripts


=== Cel ćwiczenia ===
== Module 5: Parameterization and Dynamic Queries in Power Query ==
W tym module nauczysz się:
*✔ Jak tworzyć parametry w Power Query.
*✔ Jak używać parametrów do dynamicznego filtrowania i sterowania wynikami zapytań.


=== Dostarczone dane ===
=== Objective ===
W tym ćwiczeniu użyjemy pliku:
In this module, you will learn:
* '''📂 [[Media:PQ_sales2.csv]]'''
* ✔ How to create parameters in Power Query 
oraz nowego zestawu danych
* ✔ How to use parameters for dynamic filtering and query control
* '''📂 [[Media:PQ_parameters.xlsx]]''', który zawiera wartości do dynamicznego filtrowania.


=== Instrukcje ===
=== Files Provided ===
This exercise uses the following files:


* 🔹 Krok 1: Załaduj plik CSV do Power Query
* '''📂 [[Media:PQ_sales2.csv]]''' 
# Otwórz Excela i przejdź do „Dane” → „Pobierz dane” → „Z pliku” → „Z pliku CSV”.
* '''📂 [[Media:PQ_parameters.xlsx]]''' – contains values for dynamic filtering
# Wybierz plik `PQ_sales.csv` i kliknij „Załaduj do Power Query”.
# Po załadowaniu pliku upewnij się, że Power Query rozpoznał poprawnie dane.


*🔹 Krok 2: Przetwórz tabelę `Parameters`
=== Instructions ===
# W Power Query przejdź do tabeli **`Parameters`**.
# **Transponuj tabelę** – kliknij **„Przekształć” → „Transponuj”**.
# **Ustaw pierwszy wiersz jako nagłówki** – kliknij **„Przekształć” → „Użyj pierwszego wiersza jako nagłówków”**.
# **Zmień typy danych** dla `startDate` i `endDate` na **Date**:
## Kliknij nagłówek `startDate` → wybierz typ `Date`.
## Powtórz dla `endDate`.


* 🔹 Krok 3: Utwórz osobne zapytania dla `startDate` i `endDate`
* 🔹 Step 1: Load the CSV file into Power Query 
# W tabeli `Parameters` kliknij prawym przyciskiem myszy na wartość w `startDate` → **„Dodaj jako nowe zapytanie”** (`Add as new query`).
# Open Excel and go to **Data → Get Data → From File → From Text/CSV**
# Powtórz tę operację dla `endDate`.
# Select the file `PQ_sales.csv` and load it into Power Query 
# Make sure Power Query recognizes the data correctly


* 🔹 Krok 4: Zmień typ danych w kolumnie `OrderDate` w tabeli `PQ Sales` na date
* 🔹 Step 2: Process the `Parameters` table 
# Wróć do zapytania `PQ Sales`.
# In Power Query, go to the **`Parameters`** table 
# Kolumna `OrderDate` zawiera daty w formacie `DD MM YY`.
# **Transpose the table** – click **Transform Transpose**
# **Rozdziel ją na trzy kolumny**:
# **Use the first row as headers** – click **Transform → Use First Row as Headers**
## Kliknij **„Przekształć” „Podziel kolumnę” → „Według ogranicznika”**.
# **Change the data types** for `startDate` and `endDate` to **Date**:
## Wybierz **spację** (` `) jako ogranicznik.
## Click the `startDate` column header → choose type `Date`
## Powstają trzy nowe kolumny: `OrderDate.1`, `OrderDate.2`, `OrderDate.3` (dzień, miesiąc, rok).
## Repeat for `endDate`
# **Zmień typy danych** tych kolumn na `Number` (`Int64.Type`).
# **Połącz je w poprawny format `YYYY-MM-DD`**:
## Kliknij **„Scal kolumny”** (`Merge Columns`).
## Wybierz kolejność: `OrderDate.2`, `OrderDate.3`, `OrderDate.1` (miesiąc, rok, dzień).
## Ustaw separator `/`.
## Zmień nazwę kolumny na `DateOrder`.
## Zmień jej typ na **Date**.


* 🔹 Krok 5: Dodanie dynamicznego filtra do `DateOrder`  
* 🔹 Step 3: Create separate queries for `startDate` and `endDate` 
# Otwórz **Edytor Zaawansowany** (`View` → `Advanced Editor`).
# In the `Parameters` table, right-click the value in `startDate` → **Add as New Query**
# Znajdź ostatni krok przed `in`:
# Repeat this for `endDate`


  #"Renamed Columns" = Table.RenameColumns(#"Changed Type2",{{"Merged", "DateOrder"}})
* 🔹 Step 4: Change the data type of `OrderDate` in the `PQ Sales` table to date 
 
# Go back to the `PQ Sales` query 
* 🔹 Krok 6 :Dodaj filtr:  
# The `OrderDate` column contains dates in `DD MM YY` format 
# **Split the column into three parts**: 
## Click **Transform → Split Column → By Delimiter**  
## Choose **Space** (` `) as the delimiter 
## You will get: `OrderDate.1`, `OrderDate.2`, `OrderDate.3` (day, month, year)
# **Change their types to `Number` (Int64.Type)** 
# **Merge into proper `YYYY-MM-DD` format**:
## Click **Merge Columns** 
## Order the columns as: `OrderDate.2`, `OrderDate.3`, `OrderDate.1` (month, year, day) 
## Use `/` as the separator 
## Rename the new column to `DateOrder` 
## Change its type to **Date**


* 🔹 Step 5: Add a dynamic filter to `DateOrder` 
# Open the **Advanced Editor** (`View → Advanced Editor`) 
# Find the last step before `in`, such as:
"Renamed Columns" = Table.RenameColumns(#"Changed Type2",{{"Merged", "DateOrder"}})
* 🔹 Step 6: Add the filter line:
  #"Filtered Rows" = Table.SelectRows(#"Renamed Columns", each [DateOrder] >= startDate and [DateOrder] <= endDate)
  #"Filtered Rows" = Table.SelectRows(#"Renamed Columns", each [DateOrder] >= startDate and [DateOrder] <= endDate)


Upewnij się, że startDate i endDate są w formacie Date.


Zmień końcową wartość in, aby zwracała #"Filtered Rows":
Ensure that `startDate` and `endDate` are in Date format.


Update the final `in` line to return the filtered table:
  in
  in
    #"Filtered Rows"
#"Filtered Rows"
 
* 🔹 Krok 7: Sprawdzenie wyników
 
#Kliknij „Gotowe” (Done).
#Sprawdź, czy dane są filtrowane poprawnie.
#Kliknij „Zamknij i Załaduj” (Close & Load), aby zapisać dane w Excelu
 
== Modul 6: Automatyzacja Laczenia i Odswiezania Danych w Power Query ==


=== Cel ===
W tym module nauczysz się:
*✔ Jak automatycznie importować i łączyć pliki z folderu.
*✔ Jak radzić sobie z różnymi nazwami kolumn w różnych plikach.
*✔ Jak przygotować dane do raportowania niezależnie od struktury źródłowych plików.
*✔ Jak ustawić automatyczne odświeżanie danych w Power Query.


=== Dostarczone dane ===
* 🔹 Step 7: Check the results 
W tym ćwiczeniu użyjemy zestawu wielu plików sprzedażowych, które znajdują się w jednym folderze.
# Click **Done** 
# Verify that the data is correctly filtered 
# Click **Close & Load** to load the data into Excel


'''📂 [[Media:Sales_Jan.xlsx]]''' – Sprzedaż za styczeń
== Module 6: Automating Data Combining and Refreshing in Power Query ==


'''📂 [[Media:Sales_Feb.xlsx]]''' – Sprzedaż za luty
=== Objective ===
In this module, you will learn:
* ✔ How to automatically import and combine files from a folder 
* ✔ How to handle different column names across files 
* ✔ How to prepare data for reporting regardless of source file structure 
* ✔ How to set up automatic data refresh in Power Query


'''📂 [[Media:Sales_Mar.xlsx]]''' – Sprzedaż za marzec
=== Files Provided ===
This exercise uses a set of sales files located in a single folder:


Każdy plik zawiera podobne dane, ale ma inne nazwy kolumn dla wartości sprzedaży:
'''📂 [[Media:Sales_Jan.xlsx]]''' – Sales for January 
'''📂 [[Media:Sales_Feb.xlsx]]''' – Sales for February 
'''📂 [[Media:Sales_Mar.xlsx]]''' – Sales for March 


W Sales_Jan.xlsx kolumna sprzedaży to Total Sale.
Each file contains similar data, but the sales column names differ:


W Sales_Feb.xlsx kolumna sprzedaży to Revenue.
* In *Sales_Jan.xlsx*: the sales column is named `Total Sale` 
* In *Sales_Feb.xlsx*: the column is named `Revenue
* In *Sales_Mar.xlsx*: the column is named `SalesAmount`


W Sales_Mar.xlsx kolumna sprzedaży to SalesAmount.
The goal is to combine these files into a single dataset and standardize the column names.


Celem jest połączenie tych plików w jeden zbiór i dostosowanie nazw kolumn, aby były spójne.
=== Instructions ===


=== Instrukcje ===
* Step 1: Load files from a folder 
# Open Power Query in Excel 
# Go to **Data → Get Data → From File → From Folder** 
# Select the folder containing the files (Sales_Jan.xlsx, Sales_Feb.xlsx, Sales_Mar.xlsx) 
# Click **Load** to add files to Power Query without combining them automatically


*Krok 1: Pobranie plików z folderu
* Step 2: Use M code to load the data 
#Otwórz Power Query w Excelu.
# Open **Advanced Editor** in Power Query
#Wybierz Dane → Pobierz dane → Z pliku → Z folderu.
# Paste the following M code and click **Done**:
#Wskaż folder, w którym znajdują się pliki sprzedażowe (Sales_Jan.xlsx, Sales_Feb.xlsx, Sales_Mar.xlsx).
#Kliknij Załaduj (Load), aby dodać pliki do Power Query bez automatycznego łączenia.
*Krok 2: Zastosowanie kodu M do załadowania danych
#Otwórz Zaawansowany Edytor w Power Query.
#Wklej poniższy kod M i kliknij Gotowe:


  let
  let
    // Wczytanie plików z folderu
// Load files from folder
    Source = Folder.Files("C:\Users\pathToFolder..."),
Source = Folder.Files("C:\Users\pathToFolder..."),
   
    // Dodanie kolumny, która otworzy zawartość pliku Excel
// Add a column to access the Excel file contents
    AddContent = Table.AddColumn(Source, "Custom", each Excel.Workbook([Content])),
AddContent = Table.AddColumn(Source, "Custom", each Excel.Workbook([Content])),
   
    // Rozwinięcie zawartości, aby zobaczyć wszystkie dane
/ Expand content to view all data
    ExpandContent = Table.ExpandTableColumn(AddContent, "Custom", {"Name", "Data"}, {"File Name", "Data"})
ExpandContent = Table.ExpandTableColumn(AddContent, "Custom", {"Name", "Data"}, {"File Name", "Data"})
   
   
  in
  in
    ExpandContent
ExpandContent
 
 
# After applying the code, you will see a new `Data` column


#Po zastosowaniu kodu zobaczysz tabelę z nową kolumną Data.
* Step 3: Expand the table contents 
# Click the expand icon next to the `Data` column 
# This reveals the full data from each file 
# Ensure that all relevant columns from all files are visible


*Krok 3: Rozwinięcie zawartości tabel
* Step 4: Remove unnecessary columns 
#Kliknij ikonę rozwinięcia obok kolumny Data, aby zobaczyć pełne dane z plików.
# Review the table and remove technical columns (e.g., file path) not needed for analysis 
#Upewnij się, że wszystkie kolumny z różnych plików są widoczne.
# Go to **Transform → Remove Columns** and select what to discard


*Krok 4: Usunięcie zbędnych kolumn
* Step 5: Rename columns 
# Rename the varying sales columns to a consistent name (e.g., `Sales`) 
# Use **Transform → Rename Column** to apply a uniform structure


#Sprawdź tabelę i usuń niepotrzebne kolumny (np. kolumny techniczne dotyczące plików, które nie są wymagane do analizy).
* Step 6: Remove unnecessary rows (e.g., repeated headers)
#Kliknij Przekształć → Usuń kolumny i usuń zbędne kolumny.
# Apply a filter on the column containing sales values 
*Krok 5: Nadanie nazw kolumnom
# Remove rows with repeated headers caused by merging files 
#Ustaw własne nazwy kolumn zgodnie ze spójnym formatem (np. Total Sale → Sales).
# Go to **Transform Remove Rows Remove Duplicates**, or filter manually
#Kliknij Przekształć → Zmień nazwę kolumny dla każdej kolumny, aby nadać im jednolitą strukturę.
*Krok 6: Usunięcie zbędnych wierszy (powtórzeń nagłówków)
#Zastosuj filtr na kolumnie zawierającej wartości sprzedaży.
#Usuń wiersze zawierające powtórzenia nagłówków, które mogą występować z powodu łączenia wielu plików.
#Kliknij Przekształć Usuń wiersze Usuń duplikaty lub zastosuj filtr manualnie.
*Krok 7: Automatyczne odświeżanie danych
#Przejdź do Dane → Właściwości zapytania → Odświeżaj dane przy otwieraniu pliku.
#Możesz także ustawić automatyczne odświeżanie co X minut.
#Jeśli dodasz nowy plik do folderu (np. Sales_Apr.xlsx), Power Query automatycznie pobierze dane z nowego pliku po odświeżeniu!


=== Zadanie ===
* Step 7: Enable automatic refresh 
*✔ Załaduj i połącz dane z Sales_Jan.xlsx, Sales_Feb.xlsx, Sales_Mar.xlsx.
# Go to **Data → Query Properties → Refresh data when opening the file*
*✔ Ujednolić nazwy kolumn i przekształcić dane w jednolity format.
# Optionally set automatic refresh every X minutes 
*✔ Usuń puste wiersze, zbędne kolumny i duplikaty.
# If a new file (e.g., *Sales_Apr.xlsx*) is added to the folder, Power Query will automatically include it upon refresh!
*✔ Ustaw automatyczne odświeżanie, aby nowe pliki były automatycznie dołączane.
*✔ Skorzystaj z ChatGPT do optymalizacji kodu M w Power Query.


=== Task ===
* ✔ Load and combine data from *Sales_Jan.xlsx*, *Sales_Feb.xlsx*, and *Sales_Mar.xlsx* 
* ✔ Standardize column names and format the data consistently 
* ✔ Remove empty rows, unnecessary columns, and duplicates 
* ✔ Set up auto-refresh so new files are included automatically 
* ✔ Use ChatGPT to optimize the M code in Power Query


== Modul 7: Optymalizacja Wydajnosci Zapytan w Power Query ==
== Module 7: Optimizing Query Performance in Power Query ==


=== Cel  ===
=== Objective ===
W tym module nauczysz się:
In this module, you will learn:
*✔ Jak przyspieszyć działanie Power Query w przypadku dużych zbiorów danych.
* ✔ How to speed up Power Query when working with large datasets 
*✔ Jak unikać nieefektywnych operacji, które spowalniają zapytania.
* ✔ How to avoid inefficient operations that slow down queries 
*✔ Jak korzystać z funkcji buforowania i operacji na poziomie bazy danych.
* ✔ How to use buffering and database-level transformations 
*✔ Jak minimalizować ilość przetwarzanych danych dla lepszej wydajności.
* ✔ How to minimize the amount of data processed for better performance


=== Wprowadzenie ===
=== Introduction ===
Power Query pozwala na transformację danych, ale przy dużych zbiorach może działać wolno. W tym module nauczysz się optymalnych praktyk, które pozwolą skrócić czas przetwarzania zapytań.
Power Query enables powerful data transformation, but with large datasets, performance can suffer. In this module, you will learn best practices to reduce query execution time.


=== Instrukcje ===
=== Instructions ===


*Krok 1: Unikanie niepotrzebnych operacji na całym zbiorze danych
* Step 1: Avoid unnecessary operations on the entire dataset 
#Wczytaj duży plik CSV 📂[[Media:PQSales_Large.csv]].
# Load a large CSV file: 📂[[Media:PQSales_Large.csv]]
#Sprawdź liczbę wierszy i kolumn im więcej danych, tym większe znaczenie ma optymalizacja.
# Check the number of rows and columns the more data, the more important the optimization 
#Usuń zbędne kolumny na początku zapytania, zamiast na końcu.
# Remove unnecessary columns at the beginning of the query instead of the end 
#Użyj Filtrowania wczesnego – zastosuj filtr, aby ograniczyć liczbę przetwarzanych wierszy od razu po imporcie.
# Apply early filtering to reduce the number of rows right after import


*Krok 2: Używanie funkcji buforowania (Table.Buffer)
* Step 2: Use buffering (Table.Buffer)
#Sprawdź, jak działa przetwarzanie kroków każda operacja może powodować ponowne przeliczenie całego zapytania.
# Understand how step-by-step processing works each operation may cause Power Query to recalculate previous steps 
#Dodaj krok Table.Buffer() po filtrze, aby zapobiec ponownemu przetwarzaniu danych:
# Add `Table.Buffer()` after the filter step to avoid re-processing:


  let
  let
    Source = Csv.Document(File.Contents("C:\Users\gp\Desktop\PQ\Sales_Large.csv"),[Delimiter=",", Columns=6, Encoding=1252, QuoteStyle=QuoteStyle.None]),
Source = Csv.Document(File.Contents("C:\Users\gp\Desktop\PQ\Sales_Large.csv"),[Delimiter=",", Columns=6, Encoding=1252, QuoteStyle=QuoteStyle.None]),
    FilteredRows = Table.SelectRows(Source, each [Cost] > 500),
FilteredRows = Table.SelectRows(Source, each [Cost] > 500),
    BufferedData = Table.Buffer(FilteredRows)
BufferedData = Table.Buffer(FilteredRows)
  in
  in
    BufferedData
BufferedData
 


Zastosowanie Table.Buffer() powoduje, że Power Query zapisuje wyniki kroku w pamięci, zamiast ponownie przeliczać je w kolejnych krokach.
Using `Table.Buffer()` ensures that the results are stored in memory and not recalculated at each step.


*Krok 3: Minimalizacja liczby wczytywanych wierszy
* Step 3: Minimize the number of loaded rows 
#Jeśli pracujesz z dużą bazą danych lub plikami CSV, załaduj tylko potrzebne kolumny i wiersze.
# When working with large databases or CSV files, load only the needed columns and rows 
#Zamiast pobierać wszystkie dane, użyj funkcji Keep Top Rows do pobrania np. pierwszych 1000 wierszy dla testów.
# Use **Keep Top Rows** to load e.g., the first 1000 rows for testing 
#Użyj funkcji Remove Duplicates na wczesnym etapie, aby zmniejszyć liczbę przetwarzanych danych.
# Apply **Remove Duplicates** early to reduce the volume of data being processed
*Krok 4: Optymalizacja połączeń z bazą danych
#Jeśli pracujesz z SQL Server, Power BI lub inną bazą danych, unikaj pobierania całej tabeli do Power Query.
#Zamiast tego, filtrowanie i grupowanie wykonuj na poziomie bazy danych za pomocą przekształceń natywnych SQL.


Przykład:
* Step 4: Optimize database connections 
# If working with SQL Server, Power BI, or another database, avoid importing full tables into Power Query 
# Instead, apply filtering and grouping on the database side using native SQL
 
Example:


  let
  let
    Source = Sql.Database("ServerName", "DatabaseName", [Query="SELECT OrderID, OrderDate, Customer, Product FROM Sales WHERE Cost > 500"])
Source = Sql.Database("ServerName", "DatabaseName", [Query="SELECT OrderID, OrderDate, Customer, Product FROM Sales WHERE Cost > 500"])
  in
  in
    Source
Source


Dzięki temu Power Query pobierze już przefiltrowane dane, zamiast filtrować całą tabelę w pamięci.
*Krok 5: Unikanie operacji „drill-down” na dużych zbiorach danych
#Power Query często automatycznie sugeruje „drill-down” (np. wybór pojedynczej wartości z tabeli).
#Jeśli wykonujesz operację na dużych zbiorach, staraj się pracować na całych tabelach, zamiast przekształcać pojedyncze rekordy.
*Krok 6: Automatyczne odświeżanie zoptymalizowanych zapytań
#Po zoptymalizowaniu zapytania, ustaw odświeżanie w Excelu lub Power Query, aby aktualizowało się w odpowiednich interwałach.
#W Excelu przejdź do Dane → Właściwości zapytania → Odświeżaj dane przy otwieraniu pliku.


=== Zadanie ===
This ensures Power Query pulls only the filtered data instead of processing the entire table in memory.


#Wczytaj duży plik CSV (PQSales_Large.csv).
* Step 5: Avoid "drill-down" operations on large datasets 
#Ogranicz liczbę wczytywanych wierszy i kolumn.
# Power Query often suggests drill-downs (e.g., selecting a single value from a table)
#Zastosuj Table.Buffer() i sprawdź różnicę w wydajności.
# When working with large data, operate on whole tables instead of individual records
#Jeśli korzystasz z bazy danych, zoptymalizuj zapytanie SQL.
#Ustaw automatyczne odświeżanie zoptymalizowanego zapytania.
#Skorzystaj z ChatGPT do analizy wydajności i dalszej optymalizacji kodu M.


* Step 6: Automatically refresh optimized queries 
# Once optimized, configure the query to refresh regularly 
# In Excel, go to **Data → Query Properties → Refresh data when opening the file**


== Modul 8: Tworzenie dynamicznych raportow i paneli w Excelu z Power Query ==
=== Task ===


=== Cel ===  
* Load the large CSV file (*PQSales_Large.csv*)  
W tym module nauczysz się:  
* Limit the number of loaded rows and columns  
*✔ Jak wykorzystać Power Query do dynamicznego generowania raportów.   
* Apply `Table.Buffer()` and observe performance improvements  
*✔ Jak łączyć dane z różnych źródeł w jednym raporcie.  
* If using a database, optimize your SQL query  
*✔ Jak tworzyć interaktywne raporty przy użyciu tabel przestawnych.  
* Set up auto-refresh for the optimized query  
*✔ Jak zautomatyzować odświeżanie raportów w Excelu.
* Use ChatGPT to analyze performance and further optimize M code


=== Dostarczone dane ===
== Module 8: Creating Dynamic Reports and Dashboards in Excel with Power Query ==
Do tego ćwiczenia użyjemy następujących plików: 


*📂 [[Media:PQ_Sales_Data.xlsx]] – Dane sprzedażowe.
=== Objective === 
*📂 [[Media:PQ_Regions.xlsx]] – Dane o regionach sprzedaży.
In this module, you will learn: 
*📂 [[Media:PQ_Targets.xlsx]] – Cele sprzedażowe.
* ✔ How to use Power Query to dynamically generate reports 
* ✔ How to combine data from multiple sources into a single report 
* ✔ How to create interactive reports using PivotTables 
* ✔ How to automate report refreshing in Excel


=== Instrukcje ===
=== Files Provided ===
The following files are used for this exercise: 


*Krok 1: Importowanie danych i łączenie źródeł*
* 📂 [[Media:PQ_Sales_Data.xlsx]] – Sales data 
* 📂 [[Media:PQ_Regions.xlsx]] – Sales regions 
* 📂 [[Media:PQ_Targets.xlsx]] – Sales targets


# Otwórz Power Query w Excelu.
=== Instructions ===
# Zaimportuj pliki PQ_Sales_Data.xlsx, PQ_Regions.xlsx i PQ_Targets.xlsx.
# Połącz dane ze sobą, używając klucza wspólnego – np. kolumny "Region".
# Sprawdź, czy dane są poprawnie połączone i wyświetlają się we właściwym formacie.


*Krok 2: Tworzenie dynamicznego raportu*
'''Step 1: Import and combine data sources'''


# Kliknij Zamknij i Załaduj do... i wybierz Tabelę przestawną.
# Open Power Query in Excel 
# Wstaw tabelę przestawną w nowym arkuszu i upewnij się, że źródłem danych jest Power Query.
# Import the files: *PQ_Sales_Data.xlsx*, *PQ_Regions.xlsx*, and *PQ_Targets.xlsx* 
# W polach tabeli przestawnej ustaw:
# Merge the data using a common key – for example, the `Region` column 
  * Wiersze → Region.
# Verify that the data is correctly combined and properly formatted
  * Kolumny → Miesiąc.
  * Wartości → Suma Sprzedaży.


Sprawdź poprawność wyników i sformatuj tabelę.
'''Step 2: Create a dynamic report'''


*Krok 3: Dodanie warunkowego formatowania*
# Click **Close & Load To...** and select **Pivot Table** 
# Insert the PivotTable in a new worksheet, using the Power Query output as the source 
# In the PivotTable Fields pane, set:
  * Rows → `Region` 
  * Columns → `Month` 
  * Values → `Sum of Sales`


# Wybierz kolumnę "Suma Sprzedaży" w tabeli przestawnej.
Check for accuracy and apply formatting to the table
# Kliknij Formatowanie warunkowe → Skalowanie kolorów.
# Ustaw gradientowe kolory dla niskiej i wysokiej sprzedaży.
# Zastosuj regułę "Większe niż" i podświetl wartości powyżej celu sprzedażowego (dane z PQ_Targets.xlsx).


=B5> VLOOKUP($A5,Targets!$A$2:$B$8,2,0)
'''Step 3: Add conditional formatting'''


# Select the `Sum of Sales` column in the PivotTable 
# Go to **Conditional Formatting → Color Scales** 
# Apply gradient colors to highlight low and high sales values 
# Add a rule: “Greater than” and highlight values above the sales target (from *PQ_Targets.xlsx*) using:


*Krok 4: Automatyzacja odświeżania danych*
=B5 > VLOOKUP($A5,Targets!$A$2:$B$8,2,0)


# Przejdź do Dane → Właściwości zapytania → Odświeżaj dane przy otwieraniu pliku.
'''Step 4: Automate data refreshing'''
# Możesz także ustawić odświeżanie automatyczne co X minut.
# Sprawdź, czy po dodaniu nowych danych do plików źródłowych raport aktualizuje się poprawnie.


=== Zadanie ===
# Go to **Data → Query Properties → Refresh data when opening the file** 
# Optionally set auto-refresh every X minutes 
# Test the report by updating the source files and verifying that the report refreshes correctly


# Załaduj i połącz dane z PQ_Sales_Data.xlsx, PQ_Regions.xlsx i PQ_Targets.xlsx.
=== Task ===
# Utwórz tabelę przestawną i sformatuj dane dynamicznie.
# Dodaj warunkowe formatowanie na podstawie celów sprzedażowych.
# Ustaw automatyczne odświeżanie danych.
# Skorzystaj z ChatGPT do analizy i optymalizacji zapytań Power Query.


== Podsumowanie dotychczasowych zagadnień: Zadanie kompleksowe ==
* ✔ Load and combine data from *PQ_Sales_Data.xlsx*, *PQ_Regions.xlsx*, and *PQ_Targets.xlsx* 
* ✔ Create a PivotTable and format it dynamically 
* ✔ Add conditional formatting based on sales targets 
* ✔ Set up automatic data refreshing 
* ✔ Use ChatGPT to analyze and optimize Power Query transformations


=== Cel ćwiczenia ===
== Summary: Modules 1–8 ==
W tym zadaniu podsumujesz wszystkie dotychczas poznane zagadnienia w Power Query poprzez wykonanie serii transformacji na danych dotyczących inwentaryzacji magazynowej i dostawców. Wykorzystasz import danych, filtrowanie, scalanie, dodawanie kolumn, niestandardowe funkcje i optymalizację zapytań.


=== Dostarczone dane ===
=== Objective ===
Do wykonania ćwiczenia wykorzystasz pliki:
In this exercise, you will summarize all the key concepts learned so far in Power Query by performing a series of transformations on inventory and supplier data.
* '''📂 [[Media:PQ_inventory.csv]]''' – Dane o stanie magazynowym
You will apply data import, filtering, merging, column creation, custom functions, and query optimization.
* '''📂 [[Media:PQ_suppliers.csv]]''' – Informacje o dostawcach
* '''📂 [[Media:PQ_orders.csv]]''' – Zamówienia dostaw do magazynu


=== Instrukcje ===
=== Files Provided ===
The following files are used for this exercise: 
* '''📂 [[Media:PQ_inventory.csv]]''' – Inventory stock data 
* '''📂 [[Media:PQ_suppliers.csv]]''' – Supplier information 
* '''📂 [[Media:PQ_orders.csv]]''' – Warehouse delivery orders


'''🔹 Krok 1: Importowanie danych'''
=== Instructions ===
# Otwórz Power Query w Excelu lub Power BI.
# Zaimportuj trzy pliki CSV: `PQ_inventory.csv`, `PQ_suppliers.csv`, `PQ_orders.csv`.
# Sprawdź, czy dane zostały poprawnie załadowane.


'''🔹 Krok 2: Sprawdzenie i konwersja typów danych'''
'''🔹 Step 1: Import data'''
# Upewnij się, że kolumny w każdym zbiorze mają poprawne typy danych.
# Open Power Query in Excel or Power BI 
# Problem do rozwiązania: kolumna `StockLevel` (poziom zapasów) została błędnie zaimportowana jako tekst, ponieważ zawiera wartości z jednostkami, np. `150 kg`, `200 l`, `75 szt`.
# Import the three CSV files: `PQ_inventory.csv`, `PQ_suppliers.csv`, `PQ_orders.csv`
# Przekształć kolumnę `StockLevel`, aby zawierała tylko wartości liczbowe, a jednostkę zapisz w osobnej kolumnie `Unit`.
# Make sure all datasets are loaded correctly
# Sprawdź, czy kolumna `SupplierID` została poprawnie rozpoznana jako liczba całkowita.


'''🔹 Krok 3: Scalanie danych'''
'''🔹 Step 2: Check and convert data types''' 
# Połącz `PQ_inventory.csv` z `PQ_suppliers.csv` za pomocą klucza `SupplierID`.
# Ensure all columns in each dataset have correct data types 
# Użyj `Left Outer Join`, aby zachować wszystkie rekordy magazynowe.
# Issue to solve: the `StockLevel` column was incorrectly imported as text because it contains units like `150 kg`, `200 l`, `75 pcs` 
# Następnie scal `PQ_orders.csv` z `PQ_inventory.csv`, używając `ProductID` jako klucza.
# Transform the `StockLevel` column to extract numeric values and store the unit in a new column `Unit` 
# Sprawdź, czy do tabeli magazynowej dodano informacje o dostawcach i zamówieniach.
# Verify that the `SupplierID` column is recognized as an integer
 
'''🔹 Step 3: Merge data'''
# Merge `PQ_inventory.csv` with `PQ_suppliers.csv` using the `SupplierID` key 
# Use a **Left Outer Join** to retain all inventory records 
# Then merge `PQ_orders.csv` with `PQ_inventory.csv` using the `ProductID` key 
# Verify that supplier and order info have been successfully added to the inventory table
 
'''🔹 Step 4: Create custom columns''' 
# Add a column `ReorderLevel` that flags products needing restocking when `StockLevel` is less than `MinimumStock` 
# Add a column `DaysSinceLastOrder` that calculates the number of days since the last order for each product 
# Create a custom M function that assigns order priority:


'''🔹 Krok 4: Tworzenie kolumn niestandardowych'''
# Dodaj kolumnę `ReorderLevel`, która oznaczy produkty wymagające zamówienia, gdy `StockLevel` jest mniejsze niż `MinimumStock`.
# Dodaj kolumnę `DaysSinceLastOrder`, która oblicza liczbę dni od ostatniego zamówienia na dany produkt.
# Utwórz niestandardową funkcję w M, która przypisuje priorytet zamówienia:
<pre>
<pre>
if [StockLevel] < [MinimumStock] and [DaysSinceLastOrder] > 30 then "High"  
if [StockLevel] < [MinimumStock] and [DaysSinceLastOrder] > 30 then "High"  
Line 527: Line 544:
else "Low"
else "Low"
</pre>
</pre>
# Dodaj kolumnę `OrderPriority` i przypisz do niej wynik tej funkcji.


'''🔹 Krok 5: Filtrowanie i transformacje warunkowe'''
# Add a column `OrderPriority` and apply this function
# Usuń produkty, które są w stanie `Discontinued`.
 
# Dodaj nową kolumnę `SupplierRating`, która klasyfikuje dostawców według ich niezawodności:
'''🔹 Step 5: Conditional filtering and transformations'''
# Remove products that have a `Discontinued` status 
# Add a new column `SupplierRating` that classifies suppliers by reliability:
 
<pre>
<pre>
if [OnTimeDeliveryRate] > 95 then "Excellent"  
if [OnTimeDeliveryRate] < 80 then "Excellent"  
else if [OnTimeDeliveryRate] >= 80 then "Good"  
else if [OnTimeDeliveryRate] <= 90 then "Good"  
else "Poor"
else "Poor"
</pre>
</pre>
# Sprawdź, czy klasyfikacja działa poprawnie.


'''🔹 Krok 6: Przekształcanie struktury danych'''
# Verify that the rating logic works correctly
# Wykonaj unpivotowanie kolumn `Stock_Jan`, `Stock_Feb`, `Stock_Mar`, aby uzyskać strukturę z kolumnami: `Product`, `Month`, `Stock Level`.
 
# Rozdziel kolumnę `ProductDetails` na `ProductName` i `Category`.
'''🔹 Step 6: Reshape the data structure'''
# Scal kolumny `SupplierName` i `Country`, używając ` - ` jako separatora.
# Unpivot columns `Stock_Jan`, `Stock_Feb`, `Stock_Mar` into: `Product`, `Month`, `Stock Level`
# Split the `ProductDetails` column into `ProductName` and `Category`
# Merge the `SupplierName` and `Country` columns using `" - "` as a separator
 
'''🔹 Step 7: Query optimization''' 
# Apply `Table.Buffer()` to improve performance 
# Remove unused columns and duplicates at the beginning of the transformations, not at the end 
# If working with large data, limit the loaded rows to a test sample of 1000
 
'''🔹 Step 8: Export results''' 
# Load the final query as a table into Excel 
# Test data refresh by updating source files 
# Set up auto-refresh for the query
 
=== Task ===
* ✔ Complete all the steps listed above 
* ✔ Experiment with both the graphical interface and M code 
* ✔ Apply query optimization to improve performance 
* ✔ Ensure all transformations are correct and results are as expected 
* ✔ Use ChatGPT for troubleshooting or optimizing your M script
 
== Module 9: Importing and Analyzing PDF Files in Power Query ==
 
=== Objective ===
In this module, you will learn:
 
* ✔ How to import data from PDF files into Power Query 
* ✔ How to transform data and perform analysis on business reports 
* ✔ How to visualize results and draw insights from reports
 
=== Files Provided ===
The following PDF reports are used in this exercise:
 
* 📂 [[Media:Monthly_Sales_Report_Jan2024.pdf]] – Sales Report 
* 📂 [[Media:Employee_Attendance_Q1_2024.pdf]] – Employee Attendance Report 
* 📂 [[Media:Customer_Feedback_Survey_2024.pdf]] – Customer Feedback Report
 
=== Instructions ===
 
🔹 '''Task 1: Sales Report Analysis'''
 
# Calculate total sales for all products 
# Identify the product with the highest and lowest sales 
# Compute the average transaction value based on transaction count and total sales 
# Group data by region and calculate total sales per region 
# Create a pivot table showing sales by region and product
 
🔹 '''Task 2: Employee Attendance Report Analysis'''
 
# Calculate the average attendance rate across all departments 
# Identify the department with the highest and lowest attendance 
# Add a new column classifying attendance into categories: 
## High: above 95% 
## Medium: 85%–95% 
## Low: below 85% 
# Filter the data to show only employees with low attendance 
# Create a bar chart showing average attendance by department
 
🔹 '''Task 3: Customer Feedback Report Analysis'''
 
# Calculate the average customer rating on a 1–5 scale 
# Count how many customers gave a rating of 1 or 5 
# Generate a summary report of the most frequent positive and negative comments 
# Sort the data by customer rating from lowest to highest 
# Create a pie chart showing the distribution of customer ratings
 
=== Summary ===
* ✔ Complete the analysis tasks for each report separately 
* ✔ Apply filtering, sorting, and grouping operations 
* ✔ Use pivot tables to aggregate data 
* ✔ Visualize results using charts in Excel or Power BI 
* ✔ Use ChatGPT if you encounter difficulties during analysis
 
== Module 10: Importing and Analyzing Web Data in Power Query ==
 
=== Objective ===
In this module, you will learn:
 
* ✔ How to import data from statistical tables available on Wikipedia into Power Query 
* ✔ How to transform and analyze data about countries of the world 
* ✔ How to visualize comparison results in Excel or Power BI
 
=== Data Sources ===
In this exercise, we’ll use real tabular data about countries of the world imported directly from Wikipedia. These include:
 
* 📊 **Surface area of countries** 🌍 
* 📊 **Population by country** 👥 
* 📊 **Gross Domestic Product (GDP) by country** 💰 
 
'''Sources:''' 
* [https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_area List of countries by area] 
* [https://en.wikipedia.org/wiki/List_of_countries_and_dependencies_by_population List of countries by population] 
* [https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal) List of countries by nominal GDP]
 
=== Instructions ===
 
🔹 '''Step 1: Import data from Wikipedia'''
 
# Open Power Query in Excel or Power BI 
# Choose **Get Data → From Web** 
# Enter the URL of one of the Wikipedia pages above 
# Once the available tables are loaded, select the one containing statistical data (e.g., country area, population, or GDP) 
# Click **Load to Power Query** to begin transforming the data
 
🔹 '''Step 2: Transform and clean the data'''
 
# **Remove unnecessary columns**, keeping only those relevant for analysis 
# **Change data types** so that numbers are correctly interpreted (e.g., `Area` as number, `GDP` as currency) 
# **Remove empty values** and correct any errors 
# **Rename columns** to clearer names, such as `Country`, `Area (km²)`, `Population`, `GDP (billion USD)`
 
🔹 '''Step 3: Analyze and compare countries'''
 
# **Calculate population density** by adding a new column with the formula: 
Population Density = Population / Area 


'''🔹 Krok 7: Optymalizacja zapytania'''
# **Sort countries by GDP** to identify the richest and poorest nations 
# Zastosuj `Table.Buffer()`, aby poprawić wydajność przetwarzania.
# **Compare area and population** to find the largest, smallest, and most populated countries 
# Usuń zbędne kolumny i duplikaty na początku przekształceń, a nie na końcu.
# **Apply filtering** to display only selected continents or world regions
# Jeśli dane są duże, ogranicz liczbę wczytywanych wierszy do testowych 1000.


'''🔹 Krok 8: Eksport wyników'''
🔹 '''Step 4: Visualize the results'''
# Zapisz gotowe zapytanie jako tabelę w Excelu.
# Przetestuj odświeżanie danych po zmianie wartości w plikach źródłowych.
# Ustaw automatyczne odświeżanie zapytania.


=== Zadanie ===
# Create a **pivot table** in Excel to compare area, population, and GDP  
✔ Wykonaj wszystkie kroki opisane powyżej. 
# Insert a **bar chart** to show the largest economies  
✔ Eksperymentuj zarówno z interfejsem graficznym, jak i kodem M.  
# Use a **heat map** to illustrate population density by region  
✔ Zastosuj optymalizację zapytań, aby poprawić wydajność przetwarzania.  
# Add **conditional formatting** to highlight countries with extreme statistical values
✔ Upewnij się, że transformacje działają poprawnie i wyniki są zgodne z oczekiwaniami.  
✔ Skorzystaj z ChatGPT w celu rozwiązywania problemów lub optymalizacji skryptu M. 


'''Powodzenia!'''
=== Task ===
* ✔ Import world country data from Wikipedia into Power Query 
* ✔ Transform and clean the data to make it analysis-ready 
* ✔ Calculate population density and other statistical indicators 
* ✔ Create charts and comparison tables in Excel or Power BI 
* ✔ Use ChatGPT if you encounter issues during import or analysis

Latest revision as of 12:47, 24 June 2025

Module 1: Introduction to Power Query and Basic Transformations

Objective

In this exercise, you will learn to:

  • Import data from a CSV file into Power Query.
  • Review and adjust data types, focusing on converting a date stored as text into a proper date type.
  • Apply basic data filtering.
  • Use external help (e.g., ChatGPT) to get guidance on creating custom M code, without directly copying solutions.

Files Provided

You can download the CSV file 📂Media:PQsales.csv which contains sales order data.

Instructions

  • Step 1: Import the data
  1. Open Power Query in Excel or Power BI.
  2. Import the data from the file sales.csv.
  3. Note that the *OrderDate* column was imported as text due to its format (dd/MM/yyyy).
  • Step 2: Check and convert data types
  1. Verify that each column has the correct data type.
  2. Manually transform the *OrderDate* column from text to date type.
  3. Tip: If you encounter difficulties, you can ask ChatGPT for hints on how to write an M function to convert text to date.
  • Step 3: Apply basic filtering
  1. Filter the dataset to keep only rows where the cost is greater than 200.
  2. Suggestion: Use Power Query’s graphical interface or write a simple M script to apply the filter. If needed, consult ChatGPT for implementation ideas.
  • Step 4: Review and save your work
  1. Confirm that the transformations were applied correctly by reviewing the data preview.
  2. Save the query and document the steps you have taken.

Task

Perform the steps described above in Power Query. Experiment with available transformation options and try to understand how each step affects your data. Use ChatGPT for hints or troubleshooting, but avoid copying complete solutions verbatim.

Module 2: Combining and Merging Data from Multiple Sources

Objective

In this exercise, you will learn to:

  • Import data from multiple CSV files into Power Query.
  • Merge data from different sources based on a common key.
  • Use a Left Outer Join to add customer details to sales orders.
  • Use external help (e.g., ChatGPT) to get guidance on writing custom M code, without copying complete solutions.

Files Provided

You can download the following two CSV files:

📂 Media:PQ_sales2.csv – Contains sales order data

📂 Media:PQ_customers.csv – Contains customer information

Instructions

  • Step 1: Import the data

Open Power Query in Excel or Power BI. Import data from both files: PQ_sales.csv and PQ_customers.csv. Check that both queries have been loaded correctly.

  • Step 2: Check and convert data types

Ensure that each column has the correct data type in both queries. For example, note that the *OrderDate* column in PQ_sales.csv may be imported as text due to a non-standard format. Tip: Use the transformation functions if any adjustments are needed.

  • Step 3: Merge the data

Merge the *PQ_sales.csv* query with the *PQ_customers.csv* query. Use the *Customer* column as the matching key. Choose the Left Outer Join option so that every sales order is retained along with the corresponding customer details. Suggestion: If you’re not sure how to write M code for this merge, ask ChatGPT for tips on how to merge queries.

  • Step 4: Review the merged data

Confirm that the resulting query includes additional columns (e.g., *Region*, *CustomerSince*) from the PQ_customers.csv file. Check the merged data to ensure that customer details have been correctly linked to the corresponding sales orders.

  • Step 5: Save your work

Save your query and document the transformation steps you applied.

Task

Perform the steps described above in Power Query. Experiment with both the graphical interface and custom M code to complete the merge. Use external resources (e.g., ChatGPT) for guidance or troubleshooting, but avoid copying complete solutions verbatim.

Module 3: Creating Custom Columns and Functions

Objective

In this exercise, you will learn to:

  • Create custom calculated columns in Power Query.
  • Use built-in Power Query functions to manipulate text, numbers, and dates.
  • Write custom M functions to automate transformations.
  • Use ChatGPT to assist in writing and optimizing M code.

Files Provided

The following datasets are used for this exercise:

📂Media:PQ_sales2.csv (used in previous modules) 📂Media:PQ_discounts.csv (new dataset) – contains discount rates based on product type.

Instructions

  • Step 1: Import the data

Open Power Query in Excel or Power BI. Import both files: *PQ_sales.csv* and *PQ_discounts.csv*. Ensure both tables are loaded correctly.


  • Step 2: Create a custom column for total cost

In the *PQ_sales* table, add a new custom column: Go to **Add Column → Custom Column**. Name it `TotalCost`. Create a formula to calculate the total cost as:

`Quantity * Cost`  

Click OK and review the results.


  • Step 3: Apply discounts using merge

Merge *PQ_sales* with *PQ_discounts* using the *Product* column as the key. Expand the `DiscountRate` column into the *PQ_sales* table. Add another custom column named `DiscountedPrice`:

`[TotalCost] - ([TotalCost] * [DiscountRate])`  

Check that the new column correctly applies the discounts.


  • Step 4: Create a custom function in M

Create a function to categorize products into price bands: Go to **Home → Advanced Editor**. Write an M function that takes `Cost` as input and returns a category:

Low if Cost < 500   Medium if Cost between 500 and 1500  High if Cost > 1500  



  • Step 5: Assign categories

In the *PQ_sales* table, add a custom column using the function. Name the column `PriceCategory`. Make sure the categories display correctly based on the values in the *Cost* column.

Task

  • ✔ Complete all steps in Power Query.
  • ✔ Experiment with both the graphical interface and M code.
  • ✔ Use ChatGPT for troubleshooting or refining your M scripts.

Module 4: Advanced Data Transformations in Power Query

Objective

In this module, you will learn:

  • ✔ How to pivot and unpivot data in Power Query
  • ✔ How to split and merge columns for better data structure
  • ✔ How to use conditional transformations
  • ✔ How to leverage ChatGPT to build complex M scripts

Files Provided

This exercise introduces a new dataset: 📂 Media:PQ_sales_pivot.csv – contains monthly sales data in a pivoted format.

Instructions

Step 1: Import the data Open Power Query in Excel or Power BI. Import the file *PQ_sales_pivot.csv*. Ensure the table loads correctly.


Step 2: Unpivot the data The current table has a wide format that is not ideal for analysis. Unpivot the monthly columns so the data structure becomes:

  • Product
  • Category
  • Month
  • Sales Amount

How to do it:

  1. Click **Transform → Use First Row as Headers** to make sure column names are correct.
  2. Select the month columns (e.g., Jan 2025, Feb 2025, etc.).
  3. Click **Transform → Unpivot Columns**.
  4. Rename the resulting columns:
    1. Attribute → Month
    2. Value → Sales Amount


Step 3: Splitting and merging columns

  1. The `Month` column now contains values like "Jan 2025".
  2. Split this column into `Month Name` and `Year`:
  3. Select the `Month` column.
  4. Click **Transform → Split Column → By Delimiter**.
  5. Choose space (" ") as the delimiter.
  6. Rename the new columns to `Month Name` and `Year`.
  • Example of merging columns:*

To merge `Product` and `Category`, select both columns:

  1. Click **Transform → Merge Columns**.
  2. Use `" - "` as the separator (e.g., `"Monitor - Electronics"`).


Step 4: Adding conditional transformations Add a new custom column named `Sales Performance` with the following logic:

if [Sales Amount] < 300 then "Low"
else if [Sales Amount] >= 300 and [Sales Amount] < 800 then "Medium"
else "High"


Make sure the column correctly categorizes the sales performance.

Task

  • ✔ Complete all steps in Power Query
  • ✔ Experiment with unpivoting, splitting, merging, and conditional logic
  • ✔ Use ChatGPT for troubleshooting or refining your M scripts

Module 5: Parameterization and Dynamic Queries in Power Query

Objective

In this module, you will learn:

  • ✔ How to create parameters in Power Query
  • ✔ How to use parameters for dynamic filtering and query control

Files Provided

This exercise uses the following files:

Instructions

  • 🔹 Step 1: Load the CSV file into Power Query
  1. Open Excel and go to **Data → Get Data → From File → From Text/CSV**
  2. Select the file `PQ_sales.csv` and load it into Power Query
  3. Make sure Power Query recognizes the data correctly
  • 🔹 Step 2: Process the `Parameters` table
  1. In Power Query, go to the **`Parameters`** table
  2. **Transpose the table** – click **Transform → Transpose**
  3. **Use the first row as headers** – click **Transform → Use First Row as Headers**
  4. **Change the data types** for `startDate` and `endDate` to **Date**:
    1. Click the `startDate` column header → choose type `Date`
    2. Repeat for `endDate`
  • 🔹 Step 3: Create separate queries for `startDate` and `endDate`
  1. In the `Parameters` table, right-click the value in `startDate` → **Add as New Query**
  2. Repeat this for `endDate`
  • 🔹 Step 4: Change the data type of `OrderDate` in the `PQ Sales` table to date
  1. Go back to the `PQ Sales` query
  2. The `OrderDate` column contains dates in `DD MM YY` format
  3. **Split the column into three parts**:
    1. Click **Transform → Split Column → By Delimiter**
    2. Choose **Space** (` `) as the delimiter
    3. You will get: `OrderDate.1`, `OrderDate.2`, `OrderDate.3` (day, month, year)
  4. **Change their types to `Number` (Int64.Type)**
  5. **Merge into proper `YYYY-MM-DD` format**:
    1. Click **Merge Columns**
    2. Order the columns as: `OrderDate.2`, `OrderDate.3`, `OrderDate.1` (month, year, day)
    3. Use `/` as the separator
    4. Rename the new column to `DateOrder`
    5. Change its type to **Date**
  • 🔹 Step 5: Add a dynamic filter to `DateOrder`
  1. Open the **Advanced Editor** (`View → Advanced Editor`)
  2. Find the last step before `in`, such as:
"Renamed Columns" = Table.RenameColumns(#"Changed Type2",Template:"Merged", "DateOrder")
  • 🔹 Step 6: Add the filter line:
#"Filtered Rows" = Table.SelectRows(#"Renamed Columns", each [DateOrder] >= startDate and [DateOrder] <= endDate)


Ensure that `startDate` and `endDate` are in Date format.

Update the final `in` line to return the filtered table:

in
#"Filtered Rows"


  • 🔹 Step 7: Check the results
  1. Click **Done**
  2. Verify that the data is correctly filtered
  3. Click **Close & Load** to load the data into Excel

Module 6: Automating Data Combining and Refreshing in Power Query

Objective

In this module, you will learn:

  • ✔ How to automatically import and combine files from a folder
  • ✔ How to handle different column names across files
  • ✔ How to prepare data for reporting regardless of source file structure
  • ✔ How to set up automatic data refresh in Power Query

Files Provided

This exercise uses a set of sales files located in a single folder:

📂 Media:Sales_Jan.xlsx – Sales for January 📂 Media:Sales_Feb.xlsx – Sales for February 📂 Media:Sales_Mar.xlsx – Sales for March

Each file contains similar data, but the sales column names differ:

  • In *Sales_Jan.xlsx*: the sales column is named `Total Sale`
  • In *Sales_Feb.xlsx*: the column is named `Revenue`
  • In *Sales_Mar.xlsx*: the column is named `SalesAmount`

The goal is to combine these files into a single dataset and standardize the column names.

Instructions

  • Step 1: Load files from a folder
  1. Open Power Query in Excel
  2. Go to **Data → Get Data → From File → From Folder**
  3. Select the folder containing the files (Sales_Jan.xlsx, Sales_Feb.xlsx, Sales_Mar.xlsx)
  4. Click **Load** to add files to Power Query without combining them automatically
  • Step 2: Use M code to load the data
  1. Open **Advanced Editor** in Power Query
  2. Paste the following M code and click **Done**:
let
// Load files from folder
Source = Folder.Files("C:\Users\pathToFolder..."),

// Add a column to access the Excel file contents
AddContent = Table.AddColumn(Source, "Custom", each Excel.Workbook([Content])),

/ Expand content to view all data
ExpandContent = Table.ExpandTableColumn(AddContent, "Custom", {"Name", "Data"}, {"File Name", "Data"})

in
ExpandContent


  1. After applying the code, you will see a new `Data` column
  • Step 3: Expand the table contents
  1. Click the expand icon next to the `Data` column
  2. This reveals the full data from each file
  3. Ensure that all relevant columns from all files are visible
  • Step 4: Remove unnecessary columns
  1. Review the table and remove technical columns (e.g., file path) not needed for analysis
  2. Go to **Transform → Remove Columns** and select what to discard
  • Step 5: Rename columns
  1. Rename the varying sales columns to a consistent name (e.g., `Sales`)
  2. Use **Transform → Rename Column** to apply a uniform structure
  • Step 6: Remove unnecessary rows (e.g., repeated headers)
  1. Apply a filter on the column containing sales values
  2. Remove rows with repeated headers caused by merging files
  3. Go to **Transform → Remove Rows → Remove Duplicates**, or filter manually
  • Step 7: Enable automatic refresh
  1. Go to **Data → Query Properties → Refresh data when opening the file**
  2. Optionally set automatic refresh every X minutes
  3. If a new file (e.g., *Sales_Apr.xlsx*) is added to the folder, Power Query will automatically include it upon refresh!

Task

  • ✔ Load and combine data from *Sales_Jan.xlsx*, *Sales_Feb.xlsx*, and *Sales_Mar.xlsx*
  • ✔ Standardize column names and format the data consistently
  • ✔ Remove empty rows, unnecessary columns, and duplicates
  • ✔ Set up auto-refresh so new files are included automatically
  • ✔ Use ChatGPT to optimize the M code in Power Query

Module 7: Optimizing Query Performance in Power Query

Objective

In this module, you will learn:

  • ✔ How to speed up Power Query when working with large datasets
  • ✔ How to avoid inefficient operations that slow down queries
  • ✔ How to use buffering and database-level transformations
  • ✔ How to minimize the amount of data processed for better performance

Introduction

Power Query enables powerful data transformation, but with large datasets, performance can suffer. In this module, you will learn best practices to reduce query execution time.

Instructions

  • Step 1: Avoid unnecessary operations on the entire dataset
  1. Load a large CSV file: 📂Media:PQSales_Large.csv
  2. Check the number of rows and columns – the more data, the more important the optimization
  3. Remove unnecessary columns at the beginning of the query instead of the end
  4. Apply early filtering to reduce the number of rows right after import
  • Step 2: Use buffering (Table.Buffer)
  1. Understand how step-by-step processing works – each operation may cause Power Query to recalculate previous steps
  2. Add `Table.Buffer()` after the filter step to avoid re-processing:
let
Source = Csv.Document(File.Contents("C:\Users\gp\Desktop\PQ\Sales_Large.csv"),[Delimiter=",", Columns=6, Encoding=1252, QuoteStyle=QuoteStyle.None]),
FilteredRows = Table.SelectRows(Source, each [Cost] > 500),
BufferedData = Table.Buffer(FilteredRows)
in
BufferedData


Using `Table.Buffer()` ensures that the results are stored in memory and not recalculated at each step.

  • Step 3: Minimize the number of loaded rows
  1. When working with large databases or CSV files, load only the needed columns and rows
  2. Use **Keep Top Rows** to load e.g., the first 1000 rows for testing
  3. Apply **Remove Duplicates** early to reduce the volume of data being processed
  • Step 4: Optimize database connections
  1. If working with SQL Server, Power BI, or another database, avoid importing full tables into Power Query
  2. Instead, apply filtering and grouping on the database side using native SQL

Example:

let
Source = Sql.Database("ServerName", "DatabaseName", [Query="SELECT OrderID, OrderDate, Customer, Product FROM Sales WHERE Cost > 500"])
in
Source


This ensures Power Query pulls only the filtered data instead of processing the entire table in memory.

  • Step 5: Avoid "drill-down" operations on large datasets
  1. Power Query often suggests drill-downs (e.g., selecting a single value from a table)
  2. When working with large data, operate on whole tables instead of individual records
  • Step 6: Automatically refresh optimized queries
  1. Once optimized, configure the query to refresh regularly
  2. In Excel, go to **Data → Query Properties → Refresh data when opening the file**

Task

  • Load the large CSV file (*PQSales_Large.csv*)
  • Limit the number of loaded rows and columns
  • Apply `Table.Buffer()` and observe performance improvements
  • If using a database, optimize your SQL query
  • Set up auto-refresh for the optimized query
  • Use ChatGPT to analyze performance and further optimize M code

Module 8: Creating Dynamic Reports and Dashboards in Excel with Power Query

Objective

In this module, you will learn:

  • ✔ How to use Power Query to dynamically generate reports
  • ✔ How to combine data from multiple sources into a single report
  • ✔ How to create interactive reports using PivotTables
  • ✔ How to automate report refreshing in Excel

Files Provided

The following files are used for this exercise:

Instructions

Step 1: Import and combine data sources

  1. Open Power Query in Excel
  2. Import the files: *PQ_Sales_Data.xlsx*, *PQ_Regions.xlsx*, and *PQ_Targets.xlsx*
  3. Merge the data using a common key – for example, the `Region` column
  4. Verify that the data is correctly combined and properly formatted

Step 2: Create a dynamic report

  1. Click **Close & Load To...** and select **Pivot Table**
  2. Insert the PivotTable in a new worksheet, using the Power Query output as the source
  3. In the PivotTable Fields pane, set:
 * Rows → `Region`  
 * Columns → `Month`  
 * Values → `Sum of Sales`

Check for accuracy and apply formatting to the table

Step 3: Add conditional formatting

  1. Select the `Sum of Sales` column in the PivotTable
  2. Go to **Conditional Formatting → Color Scales**
  3. Apply gradient colors to highlight low and high sales values
  4. Add a rule: “Greater than” and highlight values above the sales target (from *PQ_Targets.xlsx*) using:
=B5 > VLOOKUP($A5,Targets!$A$2:$B$8,2,0)

Step 4: Automate data refreshing

  1. Go to **Data → Query Properties → Refresh data when opening the file**
  2. Optionally set auto-refresh every X minutes
  3. Test the report by updating the source files and verifying that the report refreshes correctly

Task

  • ✔ Load and combine data from *PQ_Sales_Data.xlsx*, *PQ_Regions.xlsx*, and *PQ_Targets.xlsx*
  • ✔ Create a PivotTable and format it dynamically
  • ✔ Add conditional formatting based on sales targets
  • ✔ Set up automatic data refreshing
  • ✔ Use ChatGPT to analyze and optimize Power Query transformations

Summary: Modules 1–8

Objective

In this exercise, you will summarize all the key concepts learned so far in Power Query by performing a series of transformations on inventory and supplier data. You will apply data import, filtering, merging, column creation, custom functions, and query optimization.

Files Provided

The following files are used for this exercise:

Instructions

🔹 Step 1: Import data

  1. Open Power Query in Excel or Power BI
  2. Import the three CSV files: `PQ_inventory.csv`, `PQ_suppliers.csv`, `PQ_orders.csv`
  3. Make sure all datasets are loaded correctly

🔹 Step 2: Check and convert data types

  1. Ensure all columns in each dataset have correct data types
  2. Issue to solve: the `StockLevel` column was incorrectly imported as text because it contains units like `150 kg`, `200 l`, `75 pcs`
  3. Transform the `StockLevel` column to extract numeric values and store the unit in a new column `Unit`
  4. Verify that the `SupplierID` column is recognized as an integer

🔹 Step 3: Merge data

  1. Merge `PQ_inventory.csv` with `PQ_suppliers.csv` using the `SupplierID` key
  2. Use a **Left Outer Join** to retain all inventory records
  3. Then merge `PQ_orders.csv` with `PQ_inventory.csv` using the `ProductID` key
  4. Verify that supplier and order info have been successfully added to the inventory table

🔹 Step 4: Create custom columns

  1. Add a column `ReorderLevel` that flags products needing restocking when `StockLevel` is less than `MinimumStock`
  2. Add a column `DaysSinceLastOrder` that calculates the number of days since the last order for each product
  3. Create a custom M function that assigns order priority:
if [StockLevel] < [MinimumStock] and [DaysSinceLastOrder] > 30 then "High" 
else if [StockLevel] < [MinimumStock] then "Medium" 
else "Low"
  1. Add a column `OrderPriority` and apply this function

🔹 Step 5: Conditional filtering and transformations

  1. Remove products that have a `Discontinued` status
  2. Add a new column `SupplierRating` that classifies suppliers by reliability:
if [OnTimeDeliveryRate] < 80 then "Excellent" 
else if [OnTimeDeliveryRate] <= 90 then "Good" 
else "Poor"
  1. Verify that the rating logic works correctly

🔹 Step 6: Reshape the data structure

  1. Unpivot columns `Stock_Jan`, `Stock_Feb`, `Stock_Mar` into: `Product`, `Month`, `Stock Level`
  2. Split the `ProductDetails` column into `ProductName` and `Category`
  3. Merge the `SupplierName` and `Country` columns using `" - "` as a separator

🔹 Step 7: Query optimization

  1. Apply `Table.Buffer()` to improve performance
  2. Remove unused columns and duplicates at the beginning of the transformations, not at the end
  3. If working with large data, limit the loaded rows to a test sample of 1000

🔹 Step 8: Export results

  1. Load the final query as a table into Excel
  2. Test data refresh by updating source files
  3. Set up auto-refresh for the query

Task

  • ✔ Complete all the steps listed above
  • ✔ Experiment with both the graphical interface and M code
  • ✔ Apply query optimization to improve performance
  • ✔ Ensure all transformations are correct and results are as expected
  • ✔ Use ChatGPT for troubleshooting or optimizing your M script

Module 9: Importing and Analyzing PDF Files in Power Query

Objective

In this module, you will learn:

  • ✔ How to import data from PDF files into Power Query
  • ✔ How to transform data and perform analysis on business reports
  • ✔ How to visualize results and draw insights from reports

Files Provided

The following PDF reports are used in this exercise:

Instructions

🔹 Task 1: Sales Report Analysis

  1. Calculate total sales for all products
  2. Identify the product with the highest and lowest sales
  3. Compute the average transaction value based on transaction count and total sales
  4. Group data by region and calculate total sales per region
  5. Create a pivot table showing sales by region and product

🔹 Task 2: Employee Attendance Report Analysis

  1. Calculate the average attendance rate across all departments
  2. Identify the department with the highest and lowest attendance
  3. Add a new column classifying attendance into categories:
    1. High: above 95%
    2. Medium: 85%–95%
    3. Low: below 85%
  4. Filter the data to show only employees with low attendance
  5. Create a bar chart showing average attendance by department

🔹 Task 3: Customer Feedback Report Analysis

  1. Calculate the average customer rating on a 1–5 scale
  2. Count how many customers gave a rating of 1 or 5
  3. Generate a summary report of the most frequent positive and negative comments
  4. Sort the data by customer rating from lowest to highest
  5. Create a pie chart showing the distribution of customer ratings

Summary

  • ✔ Complete the analysis tasks for each report separately
  • ✔ Apply filtering, sorting, and grouping operations
  • ✔ Use pivot tables to aggregate data
  • ✔ Visualize results using charts in Excel or Power BI
  • ✔ Use ChatGPT if you encounter difficulties during analysis

Module 10: Importing and Analyzing Web Data in Power Query

Objective

In this module, you will learn:

  • ✔ How to import data from statistical tables available on Wikipedia into Power Query
  • ✔ How to transform and analyze data about countries of the world
  • ✔ How to visualize comparison results in Excel or Power BI

Data Sources

In this exercise, we’ll use real tabular data about countries of the world imported directly from Wikipedia. These include:

  • 📊 **Surface area of countries** 🌍
  • 📊 **Population by country** 👥
  • 📊 **Gross Domestic Product (GDP) by country** 💰

Sources:

Instructions

🔹 Step 1: Import data from Wikipedia

  1. Open Power Query in Excel or Power BI
  2. Choose **Get Data → From Web**
  3. Enter the URL of one of the Wikipedia pages above
  4. Once the available tables are loaded, select the one containing statistical data (e.g., country area, population, or GDP)
  5. Click **Load to Power Query** to begin transforming the data

🔹 Step 2: Transform and clean the data

  1. **Remove unnecessary columns**, keeping only those relevant for analysis
  2. **Change data types** so that numbers are correctly interpreted (e.g., `Area` as number, `GDP` as currency)
  3. **Remove empty values** and correct any errors
  4. **Rename columns** to clearer names, such as `Country`, `Area (km²)`, `Population`, `GDP (billion USD)`

🔹 Step 3: Analyze and compare countries

  1. **Calculate population density** by adding a new column with the formula:
Population Density = Population / Area  
  1. **Sort countries by GDP** to identify the richest and poorest nations
  2. **Compare area and population** to find the largest, smallest, and most populated countries
  3. **Apply filtering** to display only selected continents or world regions

🔹 Step 4: Visualize the results

  1. Create a **pivot table** in Excel to compare area, population, and GDP
  2. Insert a **bar chart** to show the largest economies
  3. Use a **heat map** to illustrate population density by region
  4. Add **conditional formatting** to highlight countries with extreme statistical values

Task

  • ✔ Import world country data from Wikipedia into Power Query
  • ✔ Transform and clean the data to make it analysis-ready
  • ✔ Calculate population density and other statistical indicators
  • ✔ Create charts and comparison tables in Excel or Power BI
  • ✔ Use ChatGPT if you encounter issues during import or analysis