patternsqlMinor
GROUP BY two columns
Viewed 0 times
twocolumnsgroup
Problem
I want to count two columns, but need to get the results of first column in one row.
This query gives me
but I need to get
as I want to update another table with these values, and with this row structure, I can update the country table row by row as I get from the above query.
NOTE:
SELECT country, COUNT(*)
FROM table1
GROUP BY country, typeThis query gives me
country type COUNT(*)
Canada first 22
Canada second 42
Canada third 15
Australia second 23
Australia third 18but I need to get
country type_first type_second type_third
Canada 22 42 15
Australia 23 18 0as I want to update another table with these values, and with this row structure, I can update the country table row by row as I get from the above query.
UPDATE country SET first=x, second=x, third=xNOTE:
type column is ENUM with predefined values.Solution
Looks like you want something like:
SELECT country
, sum(case when type = 'first' then 1 else 0 end) as type_first
, sum(case when type = 'second' then 1 else 0 end) as type_second
, sum(case when type = 'third' then 1 else 0 end) as type_third
FROM table1
GROUP BY countryCode Snippets
SELECT country
, sum(case when type = 'first' then 1 else 0 end) as type_first
, sum(case when type = 'second' then 1 else 0 end) as type_second
, sum(case when type = 'third' then 1 else 0 end) as type_third
FROM table1
GROUP BY countryContext
StackExchange Database Administrators Q#28406, answer score: 5
Revisions (0)
No revisions yet.