Ask Your Question
2

How can a pivot table be created in MySQL to display attendance data according to weekdays of the week?

asked 2023-05-21 05:38:57 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-21 06:07:02 +0000

qstack gravatar image

Assuming the attendance data is stored in a table named "attendance" with columns "id", "date", "studentname" and "presentstatus", the following SQL query can be used to create a pivot table that displays attendance data for each weekday:

SELECT
  COUNT(CASE WHEN DAYOFWEEK(date) = 1 THEN present_status END) AS 'Sunday',
  COUNT(CASE WHEN DAYOFWEEK(date) = 2 THEN present_status END) AS 'Monday',
  COUNT(CASE WHEN DAYOFWEEK(date) = 3 THEN present_status END) AS 'Tuesday',
  COUNT(CASE WHEN DAYOFWEEK(date) = 4 THEN present_status END) AS 'Wednesday',
  COUNT(CASE WHEN DAYOFWEEK(date) = 5 THEN present_status END) AS 'Thursday',
  COUNT(CASE WHEN DAYOFWEEK(date) = 6 THEN present_status END) AS 'Friday',
  COUNT(CASE WHEN DAYOFWEEK(date) = 7 THEN present_status END) AS 'Saturday'
FROM attendance
GROUP BY student_name

The query uses the DAYOFWEEK function to extract the weekday number from the date column, and then uses the COUNT function with a conditional statement (CASE) to count the number of times a student was present on each weekday. The result is grouped by student_name to show the pivot table.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-21 05:38:57 +0000

Seen: 8 times

Last updated: May 21 '23