Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

sql - Pivoting data in MS Access

I have a query that I've created to pull student IDs and meal items they have taken over a month long period. I would like to count the numbers of each item (Breakfast, Lunch, Snack) taken by a student over the course of the month.

It appears there's too much data for access to handle in a Pivot Table report, so I was hoping there was a SQL query I could run instead.

Here's the current query I've created:

SELECT April2013.SID, MenuItems.MealType AS Apr2013Meal  
FROM April2013 LEFT JOIN MenuItems ON MenuItems.Item=April2013.Item;  

Current output:

+-----+-----------+  
| SID |   Meal    |  
+-----+-----------+  
| 001 | Lunch     |  
| 002 | Lunch     |  
| 003 | Breakfast |  
| 004 | Snack     |  
| 005 | Lunch     |
| 006 | Lunch     |  
| 001 | Breakfast |  
| 003 | Snack     |  
| 004 | Breakfast |  
+-----+-----------+

Here's how I'd like it to look:

+-----+-----------+-------+---------+  
| SID | Breakfast | Lunch | Snack   |  
+-----+-----------+-------+---------+  
| 001 |         3 |    10 |     1   |  
| 002 |         4 |     8 |    10   |  
| 003 |        18 |     2 |     7   |  
| 004 |         6 |     7 |     2   |  
+-----+-----------+-------+---------+  
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can pivot the data using TRANSFORM:

TRANSFORM COUNT(MenuItems.MealType)
SELECT April2013.SID, MenuItems.MealType
FROM April2013 
LEFT JOIN MenuItems 
  ON MenuItems.Item=April2013.Item
GROUP BY April2013.SID
PIVOT MenuItems.MealType; 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...