🎯 Mục tiêu bài học
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
📖 Bảng Thuật Ngữ Quan Trọng
| Thuật ngữ | Tiếng Việt | Mô tả |
|---|---|---|
| Append | Ghép dọc | Stack rows từ nhiều tables (UNION) |
| Merge | Ghép ngang | JOIN tables theo common column |
| Left Outer Join | Nối trái | Giữ tất cả left + matches right |
| Inner Join | Nối trong | Chỉ rows match cả hai bảng |
| Anti Join | Nối loại trừ | Rows KHÔNG match |
| Group By | Nhóm theo | Tổng hợp data theo categories |
| Pivot | Xoay ngang | Long → wide format |
| Unpivot | Xoay dọc | Wide → long format |
| M Language | Ngôn ngữ M | Code behind Power Query |
| Parameter | Tham 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?
📦 1. Append Queries (Ghép dọc)
1.1 Append là gì?
Append = Stack rows từ nhiều tables lên nhau (UNION trong SQL).
📅Table Jan
| Date | Region | Revenue |
|---|---|---|
| Jan-01 | North | 45K |
| Jan-15 | South | 32K |
✅Appended Result
| Date | Region | Revenue |
|---|---|---|
| Jan-01 | North | 45K |
| Jan-15 | South | 32K |
| Feb-01 | North | 51K |
| Feb-12 | East | 28K |
💡 Append = ghép dọc (stack rows). Column names phải match — nếu khác → null values
1.2 Append Two / Multiple Tables
Home → Append QueriesTwo tables: Table Jan + Table FebThree or more tables: Jan + Feb + Mar + ...1.3 Append from Folder
Data → Get Data → From Folder → Select folderScenario: 12 monthly CSVs trong 1 folder→ Combine & Transform → All files merged automatically!1. List all files2. Apply same transform to each3. Append all results4. 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?
🔗 2. Merge Queries (Ghép ngang)
2.1 Merge là gì?
Merge = JOIN tables dựa trên common column (JOIN trong SQL).
📦Orders
| OrderID | ProductID | Qty |
|---|---|---|
| 001 | P01 | 5 |
| 002 | P02 | 3 |
| 003 | P99 | 1 |
💻Products
| ProductID | Name | Price |
|---|---|---|
| P01 | Laptop | 25M |
| P02 | Phone | 12M |
✅Merged Result
| OrderID | ProductID | Qty | Name | Price |
|---|---|---|---|---|
| 001 | P01 | 5 | Laptop | 25M |
| 002 | P02 | 3 | Phone | 12M |
| 003 | P99 | 1 | null | null |
Left Join giữ tất cả left rows + match right. Không match → null
2.2 Join Types
| Join Type | Use Case |
|---|---|
| Left Outer | Giữ tất cả orders, thêm product info |
| Right Outer | All products, kể cả chưa có orders |
| Full Outer | Tất cả data, kể cả không match |
| Inner | Chỉ orders có product info |
| Left Anti | Orders có ProductID không tồn tại |
| Right Anti | Products chưa có orders nào |
2.3 Expand 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 prefixLeft 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?
📊 3. Group By
3.1 Basic Group By
📊Group By Input
| Region | Product | Revenue |
|---|---|---|
| North | Laptop | 45K |
| North | Phone | 12K |
| South | Laptop | 38K |
| South | Phone | 15K |
✅Grouped Result
| Region | Total Revenue | Count |
|---|---|---|
| North | 57K | 2 |
| South | 53K | 2 |
💡 Group By: Region → Sum(Revenue) + Count Rows
3.2 Advanced Group By
Group By: Region AND ProductTotal Revenue = Sum of RevenueOrder Count = Count RowsAvg Order Value = Average of Revenue3.3 Group By with All Rows
Group By: RegionNew 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?
🔄 4. Pivot / Unpivot
4.1 Unpivot (rộng → dọc)
↔️Wide Format
| Product | Jan | Feb | Mar |
|---|---|---|---|
| Laptop | 45K | 51K | 48K |
| Phone | 12K | 15K | 18K |
⬇️Long Format (Unpivoted)
| Product | Attribute | Value |
|---|---|---|
| Laptop | Jan | 45K |
| Laptop | Feb | 51K |
| Laptop | Mar | 48K |
| Phone | Jan | 12K |
| Phone | Feb | 15K |
| Phone | Mar | 18K |
💡 Unpivot Other Columns: Wide → Long format. Tốt hơn cho PivotTables, charts, analysis
Steps:
- Select "Product" column
- 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)
Transform → Pivot ColumnValues Column: RevenueAggregate: SumUnpivot 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?
💻 5. M Language Basics
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
1View → Advanced Editor2 3let4 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] > 013 )14in15 #"Filtered Rows"5.3 Cấu trúc M
1let2 step1 = action1, // Each step = variable assignment3 step2 = action2(step1),4 step3 = action3(step2)5in6 step3 // Final output5.4 Useful M Functions
1// Text2Text.Upper("hello") // "HELLO"3Text.Contains("Hello World", "World") // true4 5// Number6Number.Round(3.14159, 2) // 3.147 8// Date9Date.Year(#date(2026, 3, 15)) // 202610Date.AddMonths(#date(2026, 1, 1), 3) // 4/1/202611 12// Table13Table.RowCount(myTable) // 100014Table.AddColumn(table, "New", each [Col1] * 2)5.5 Custom Column với M
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?
⚙️ 6. Parameters
6.1 Create Parameter
Home → Manage Parameters → New ParameterName: FilePathType: TextCurrent Value: "C:\Data\January.csv"6.2 Use Parameter
1Trong M code:2Source = Csv.Document(File.Contents(FilePath))3 4→ Thay đổi Parameter value → Query chạy với file khác6.3 Parameterized Queries
Parameter: SelectedMonth = "January"Query: Filter where Month = SelectedMonth→ Đổi parameter → Data changes!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?
🏋️ 7. Thực hành: ETL Pipeline
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:
sales_jan.csv— Sales dataproducts.xlsx— Product mastertargets.xlsx— Sales targets
Pipeline Steps
Step 1: Import sales CSV → Clean & transformStep 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 tableStep 6: Load to worksheet + PivotTableNext month: Update sales CSV → Refresh All → Done! ✅Best Practices
📁 Raw Data └─ Import_Sales_CSV └─ Import_Products📁 Transform └─ Clean_Sales └─ Merge_Products📁 Output └─ Final_Report └─ Summary_by_Region✅ Filter rows early✅ Remove columns early✅ Use native PQ functions❌ Don't load intermediate queries to worksheetCheckpoint
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!
� 8. Tổng Kết
Kiến thức đã học
| Chủ đề | Nội dung chính | Tầm quan trọng |
|---|---|---|
| Append | Ghép dọc, combine from folder | Merge monthly data |
| Merge | 6 JOIN types, expand columns | Enrich data |
| Group By | Single/multiple aggregations | Summarize |
| Pivot/Unpivot | Wide ↔ long format | Data reshaping |
| M Language | Syntax, functions, custom columns | Advanced transforms |
| Parameters | Dynamic queries, linked to cells | User-friendly reports |
Câu hỏi tự kiểm tra
- Append khác Merge như thế nào?
- Khi nào dùng Left Join vs Inner Join?
- Pivot và Unpivot dùng trong trường hợp nào?
- 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
