SQL Tutorial - Transform Table Structure | SQL Pivot table | CASE statement in SQL

Published: 11 April 2023
on channel: SQL Coder
711
5

#sql #sqlfordatascience #sqlinterviewquestions
Tricky SQL queries for interview
Title: SQL Tutorial: Transforming Table Structure with CASE Statements
Description: Learn how to transform table structure with CASE statements in SQL. This tutorial covers the basics of using MAX() function with CASE statements to pivot data and convert rows to columns. It includes step-by-step explanations and practical examples of how to use this technique to create summary reports in a more efficient way.
SQL, CASE statement, MAX function, pivot table, transform table, rows to columns, summary report, SQL tutorial.

CREATE TABLE event_data (
date DATE,
count INT,
event VARCHAR(20)
);

INSERT INTO event_data (date, count, event)
VALUES
('2023-03-29', 10, 'Impression'),
('2023-03-29', 2, 'Click'),
('2023-03-29', 1, 'Login'),
('2023-03-31', 12, 'Impression'),
('2023-03-31', 3, 'Click'),
('2023-03-31', 0, 'Login'),
('2023-04-01', 13, 'Impression'),
('2023-04-01', 4, 'Click'),
('2023-04-01', 3, 'Login');

SELECT
Date,
MAX(CASE WHEN Event = 'Impression' THEN Count ELSE 0 END) AS Impression,
MAX(CASE WHEN Event = 'Click' THEN Count ELSE 0 END) AS Click,
MAX(CASE WHEN Event = 'Login' THEN Count ELSE 0 END) AS Login
FROM table_name
GROUP BY Date;

✅ To learn more, visit us at https://visionforanalytics.com/
✅ Join our WhatsApp group to ask any questions you may have!https://chat.whatsapp.com/LTLprgdpVIh...
✅ Subscribe to the YouTube channel here:
   / @sqlcoder  


On this page of the site you can watch the video online SQL Tutorial - Transform Table Structure | SQL Pivot table | CASE statement in SQL with a duration of hours minute second in good quality, which was uploaded by the user SQL Coder 11 April 2023, share the link with friends and acquaintances, this video has already been watched 711 times on youtube and it was liked by 5 viewers. Enjoy your viewing!