'I cannot figure out how to change this into a table that has only one row and no null values. Is there a way to make this a loop?
DELETE FROM summary;
INSERT INTO summary(g_rating_total)
SELECT COUNT(rating) FROM detailed
WHERE rating = 'G';
INSERT INTO summary(pg_rating_total)
SELECT COUNT(rating) FROM detailed
WHERE rating = 'PG';
INSERT INTO summary(pg13_rating_total)
SELECT COUNT(rating) FROM detailed
WHERE rating = 'PG-13';
INSERT INTO summary(r_rating_total)
SELECT COUNT(rating) FROM detailed
WHERE rating = 'R';
INSERT INTO summary(nc17_rating_total)
SELECT COUNT(rating) FROM detailed
WHERE rating = 'NC-17';
INSERT INTO summary(total_movies)
SELECT COUNT(rating) FROM detailed;
SELECT * FROM summary;
I am trying to get the total count of each different rating and insert them into another premade table name summary. I had to initially create a summary table and detail table put data into details from multiple other tables than transform that data into something that populates the summary table. The issue I am having is inserting the count result into the summary table without creating 6 rows where each iteration of COUNT() adds a new row with null values for all previous and new rows for each column.
Solution 1:[1]
Just use a case statement for each column e.g.
INSERT INTO summary(g_rating_total, pg_rating_total, …)
SELECT
SUM(CASE WHEN rating = 'G' Then 1 else 0 end)
, SUM(CASE WHEN rating = 'PG' Then 1 else 0 end),
,…
FROM detailed;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | NickW |
