MinAI - Về trang chủ
Hướng dẫn
9/1345 phút
Đang tải...

Power Query Advanced

Merge, Append queries, Parameters, M Language basics và Custom Functions

0

🎯 Mục tiêu bài học

TB5 min

Sau bài học này, bạn sẽ:

✅ Append queries (ghép dọc, combine from folder)

✅ Merge queries (6 JOIN types, expand columns)

✅ Sử dụng Group By cho aggregations

✅ Pivot / Unpivot transformations

✅ Viết M Language cơ bản và Custom Columns

Thời gian: 45 phút | Độ khó: Advanced | Yêu cầu: Hoàn thành Bài 8 - Power Query Basics

1

📖 Bảng Thuật Ngữ Quan Trọng

TB5 min
Thuật ngữTiếng ViệtMô tả
AppendGhép dọcStack rows từ nhiều tables (UNION)
MergeGhép ngangJOIN tables theo common column
Left Outer JoinNối tráiGiữ tất cả left + matches right
Inner JoinNối trongChỉ rows match cả hai bảng
Anti JoinNối loại trừRows KHÔNG match
Group ByNhóm theoTổng hợp data theo categories
PivotXoay ngangLong → wide format
UnpivotXoay dọcWide → long format
M LanguageNgôn ngữ MCode behind Power Query
ParameterTham sốVariable cho dynamic queries

Checkpoint

Append = UNION (ghép dọc), Merge = JOIN (ghép ngang), Unpivot = wide→long. Đây là 3 operations quan trọng nhất trong Power Query Advanced. Bạn phân biệt được chưa?

2

📦 1. Append Queries (Ghép dọc)

TB5 min

1.1 Append là gì?

Append = Stack rows từ nhiều tables lên nhau (UNION trong SQL).

📅Table Jan

DateRegionRevenue
Jan-01North45K
Jan-15South32K
⬇️
APPEND (UNION)

Appended Result

DateRegionRevenue
Jan-01North45K
Jan-15South32K
Feb-01North51K
Feb-12East28K

💡 Append = ghép dọc (stack rows). Column names phải match — nếu khác → null values

1.2 Append Two / Multiple Tables

fxAppend Queries
Home → Append Queries
Two tables: Table Jan + Table Feb
Three or more tables: Jan + Feb + Mar + ...

1.3 Append from Folder

fxAppend from Folder
Data → Get Data → From Folder → Select folder
Scenario: 12 monthly CSVs trong 1 folder
→ Combine & Transform → All files merged automatically!
Power Query tự:
1. List all files
2. Apply same transform to each
3. Append all results
4. Add "Source.Name" column (filename)

Append from Folder = automation tuyệt vời cho monthly reports. Thêm file mới vào folder → Refresh → data tự include. Không cần touch query!

Checkpoint

Append = ghép rows dọc (UNION SQL). From Folder tự combine nhiều files cùng folder. Column names phải match — nếu khác → null values. Bạn đã append monthly data chưa?

3

🔗 2. Merge Queries (Ghép ngang)

TB5 min

2.1 Merge là gì?

Merge = JOIN tables dựa trên common column (JOIN trong SQL).

📦Orders

OrderIDProductIDQty
001P015
002P023
003P991
🔗 Key
ProductID

💻Products

ProductIDNamePrice
P01Laptop25M
P02Phone12M
Left Outer Join

Merged Result

OrderIDProductIDQtyNamePrice
001P015Laptop25M
002P023Phone12M
003P991nullnull

Left Join giữ tất cả left rows + match right. Không match → null

2.2 Join Types

Join TypeUse Case
Left OuterGiữ tất cả orders, thêm product info
Right OuterAll products, kể cả chưa có orders
Full OuterTất cả data, kể cả không match
InnerChỉ orders có product info
Left AntiOrders có ProductID không tồn tại
Right AntiProducts chưa có orders nào

2.3 Expand Merged Columns

fxExpand Merged Columns
Sau Merge → Cột mới "Products" hiện dạng [Table]
→ Click ⇔ expand button
→ Chọn columns cần: ☑ Name, ☑ Price
→ ☐ Use original column name as prefix

Left Anti Join là tool mạnh cho data quality! Tìm records không match — ví dụ orders có ProductID không tồn tại trong Products table. Dùng để audit data integrity.

Checkpoint

Merge = JOIN bảng theo key column. 6 loại: Left/Right/Full Outer, Inner, Left/Right Anti. Sau Merge phải Expand cột [Table]. Anti Join = tìm missing matches. Bạn đã merge tables chưa?

4

📊 3. Group By

TB5 min

3.1 Basic Group By

📊Group By Input

RegionProductRevenue
NorthLaptop45K
NorthPhone12K
SouthLaptop38K
SouthPhone15K
📊
GROUP BY Region

Grouped Result

RegionTotal RevenueCount
North57K2
South53K2

💡 Group By: Region → Sum(Revenue) + Count Rows

3.2 Advanced Group By

fxAdvanced Group By
Multiple groups + Multiple aggregations
Group By: Region AND Product
Total Revenue = Sum of Revenue
Order Count = Count Rows
Avg Order Value = Average of Revenue

3.3 Group By with All Rows

fxGroup By — All Rows
Group By: Region
New column: AllData (Operation: All Rows)
Result: Mỗi row chứa sub-table
→ Useful for advanced operations sau đó

Checkpoint

Group By = aggregate data theo categories. Basic: 1 group, 1 aggregation. Advanced: multiple groups + aggregations. All Rows giữ nguyên detail data. Bạn đã dùng Group By chưa?

5

🔄 4. Pivot / Unpivot

TB5 min

4.1 Unpivot (rộng → dọc)

↔️Wide Format

ProductJanFebMar
Laptop45K51K48K
Phone12K15K18K
🔄
UNPIVOT

⬇️Long Format (Unpivoted)

ProductAttributeValue
LaptopJan45K
LaptopFeb51K
LaptopMar48K
PhoneJan12K
PhoneFeb15K
PhoneMar18K

💡 Unpivot Other Columns: Wide → Long format. Tốt hơn cho PivotTables, charts, analysis

Steps:

  1. Select "Product" column
  2. Transform → Unpivot Other Columns

Tại sao Unpivot? Long format tốt hơn cho PivotTables, charts, analysis.

4.2 Pivot (dọc → rộng)

4.2 Pivot (dọc → rộng)

fxPivot Column
Transform → Pivot Column
Values Column: Revenue
Aggregate: Sum
💡 Ngược lại Unpivot — chuyển từ long → wide format.

Unpivot là operation bạn sẽ dùng RẤT NHIỀU. Data từ accounting, HR, surveys thường ở wide format. Unpivot → long format = ready for analysis, PivotTables, visualization.

Checkpoint

Unpivot = wide → long (tốt cho analysis). Pivot = long → wide (tốt cho reporting). Unpivot Other Columns là cách dùng phổ biến nhất. Bạn đã transform data format chưa?

6

💻 5. M Language Basics

TB5 min

5.1 M Language là gì?

M = Data mashup language power behind Power Query. Mỗi step tạo ra 1 dòng M code.

5.2 View M Code

Ví dụ
1View → Advanced Editor
2
3let
4 Source = Csv.Document(File.Contents("C:\data.csv")),
5 #"Promoted Headers" = Table.PromoteHeaders(Source),
6 #"Changed Type" = Table.TransformColumnTypes(
7 #"Promoted Headers",
8 {{"Date", type date}, {"Revenue", type number}}
9 ),
10 #"Filtered Rows" = Table.SelectRows(
11 #"Changed Type",
12 each [Revenue] > 0
13 )
14in
15 #"Filtered Rows"

5.3 Cấu trúc M

Ví dụ
1let
2 step1 = action1, // Each step = variable assignment
3 step2 = action2(step1),
4 step3 = action3(step2)
5in
6 step3 // Final output

5.4 Useful M Functions

m
1// Text
2Text.Upper("hello") // "HELLO"
3Text.Contains("Hello World", "World") // true
4
5// Number
6Number.Round(3.14159, 2) // 3.14
7
8// Date
9Date.Year(#date(2026, 3, 15)) // 2026
10Date.AddMonths(#date(2026, 1, 1), 3) // 4/1/2026
11
12// Table
13Table.RowCount(myTable) // 1000
14Table.AddColumn(table, "New", each [Col1] * 2)

5.5 Custom Column với M

Ví dụ
1Add Column → Custom Column:
2Name: "Revenue_Category"
3Formula:
4 if [Revenue] > 50000 then "High"
5 else if [Revenue] > 20000 then "Medium"
6 else "Low"

Bạn không cần học M sâu để dùng Power Query hiệu quả. GUI tạo 90% code. Chỉ cần biết Custom Column formula + đọc Advanced Editor khi debug. Học dần khi cần!

Checkpoint

M Language = code behind Power Query. Cấu trúc: let...in. GUI tạo 90% code tự động. Chỉ cần biết Custom Column formula và đọc Advanced Editor khi debug. Bạn đã xem M code chưa?

7

⚙️ 6. Parameters

TB5 min

6.1 Create Parameter

fxCreate Parameter
Home → Manage Parameters → New Parameter
Name: FilePath
Type: Text
Current Value: "C:\Data\January.csv"

6.2 Use Parameter

Ví dụ
1Trong M code:
2Source = Csv.Document(File.Contents(FilePath))
3
4→ Thay đổi Parameter value → Query chạy với file khác

6.3 Parameterized Queries

fxParameterized Queries
Scenario: Chạy query cho nhiều months
Parameter: SelectedMonth = "January"
Query: Filter where Month = SelectedMonth
→ Đổi parameter → Data changes!
Kết hợp với Drop-down trong Excel
Cell A1 = "January"
Parameter linked to cell A1
→ User chọn month → Data auto-updates ✅

Checkpoint

Parameters biến queries thành dynamic — đổi file path, filter value, date range mà không cần edit query. Link Parameter với Excel cell → user-friendly interactive reports. Bạn đã tạo parameter chưa?

8

🏋️ 7. Thực hành: ETL Pipeline

TB5 min
Thực hành trên Excel

Build ETL pipeline hoàn chỉnh — kỹ năng quan trọng nhất cho Data Analyst!

Scenario

Mỗi tháng nhận 3 files:

  1. sales_jan.csv — Sales data
  2. products.xlsx — Product master
  3. targets.xlsx — Sales targets

Pipeline Steps

fxETL Pipeline Steps
Step 1: Import sales CSV → Clean & transform
Step 2: Import products → Merge vào sales (add Name, Category)
Step 3: Import targets → Merge vào sales (add Target)
Step 4: Add calculated columns (Achievement %, Status)
Step 5: Group By Region → Summary table
Step 6: Load to worksheet + PivotTable
Next month: Update sales CSV → Refresh All → Done! ✅

Best Practices

fxQuery Organization & Performance
Query Organization
📁 Raw Data
└─ Import_Sales_CSV
└─ Import_Products
📁 Transform
└─ Clean_Sales
└─ Merge_Products
📁 Output
└─ Final_Report
└─ Summary_by_Region
Performance
✅ Filter rows early
✅ Remove columns early
✅ Use native PQ functions
❌ Don't load intermediate queries to worksheet

Checkpoint

Bạn đã build được ETL Pipeline với Append + Merge + Group By chưa? Kiểm tra: query dependencies đúng thứ tự, và chỉ load Final_Report ra worksheet!

9

� 8. Tổng Kết

TB5 min

Kiến thức đã học

Chủ đềNội dung chínhTầm quan trọng
AppendGhép dọc, combine from folderMerge monthly data
Merge6 JOIN types, expand columnsEnrich data
Group BySingle/multiple aggregationsSummarize
Pivot/UnpivotWide ↔ long formatData reshaping
M LanguageSyntax, functions, custom columnsAdvanced transforms
ParametersDynamic queries, linked to cellsUser-friendly reports

Câu hỏi tự kiểm tra

  1. Append khác Merge như thế nào?
  2. Khi nào dùng Left Join vs Inner Join?
  3. Pivot và Unpivot dùng trong trường hợp nào?
  4. M Language có ưu điểm gì so với GUI?

Bài tiếp theo: Dashboard Design — Thiết kế dashboard chuyên nghiệp

Key Takeaways:

  • Append = ghép dọc (UNION) — combine monthly/regional data
  • Merge = ghép ngang (JOIN) — 6 loại join, mở rộng columns
  • Group By cho summarize, Pivot/Unpivot cho data reshaping
  • M Language cho advanced transforms và custom functions
  • Parameters cho dynamic queries liên kết với cells