I have a dataset like this where some rows are useful, but corrupted.
create table pages (
page varchar,
cat varchar,
hits int
);
insert into pages values
(1, 'asdf', 1),
(1, 'fdsa', 2),
(1, 'Apples', 321),
(2, 'gwegr', 30),
(2, 'hsgsdf', 2),
(2, 'Bananas', 321);
I want to know the correct category for each page, and the total hits. The correct category is the one with the most hits. I'd like to have a dataset like:
page | category | sum_of_hits
-----------------------------
1 | Apples | 324
2 | Bananas | 353
The furthest I can get is:
SELECT page,
last_value(cat) over (partition BY page ORDER BY hits) as category,
sum(hits) as sum_of_hits
FROM pages
GROUP BY 1, 2
But it is erroring: ERROR: column "pages.hits" must appear in the GROUP BY clause or be used in an aggregate function Position: 83.
I tried putting the hits in an aggregate - ORDER BY max(hits) but that doesn't make sense and isn't what I want.