我有一张动物桌子,上面有每只动物的穴位,颜色和名称。
create table animals (
category text,
color text,
name text,
points numeric
)
insert into animals values ('CATS', 'WHITE', 'FLUFFY', 1234)
insert into animals values ('CATS', 'WHITE', 'FLUFFY', 2568)
insert into animals values ('CATS', 'WHITE', 'SALLY', 124)
insert into animals values ('CATS', 'WHITE', 'SALLY', 12401)
insert into animals values ('CATS', 'WHITE', 'MR KITTY', 101)
insert into animals values ('CATS', 'WHITE', 'MR KITTY', 1761)
insert into animals values ('CATS', 'BLACK', 'DARTH CATHER', 1761)
insert into animals values ('CATS', 'BLACK', 'DARTH CATHER', 2361)
insert into animals values ('CATS', 'BLACK', 'ITS A TRAP', 171)
insert into animals values ('CATS', 'BLACK', 'HAN SOLO', 1713)
insert into animals values ('DOGS', 'BROWN', 'PLUTO', 1761)
insert into animals values ('DOGS', 'BROWN', 'DUFFY', 23611)
insert into animals values ('DOGS', 'BROWN', 'PICACHOU', 1171)
insert into animals values ('DOGS', 'BROWN', 'DUFFY', 17123)
insert into animals values ('DOGS', 'BLACK', 'MICKEY', 17361)
insert into animals values ('DOGS', 'BLACK', 'JACKSON', 23361)
insert into animals values ('DOGS', 'BLACK', 'BA', 1751)
insert into animals values ('DOGS', 'BLACK', 'MACGUYVER', 17513)
insert into animals values ('FISH', 'YELLOW', 'LENON', 1571)
insert into animals values ('FISH', 'YELLOW', 'BEUSCONI', 17153)
我需要返回类似于Excel数据透视表的输出的sql输出: (按数据组中点的总和以适当的降序排列)
我真的很喜欢这个查询:
with data_grouped as
(
Select
COALESCE ( category, 'Total'::text) as category,
COALESCE ( color, 'Total'::text) as color,
COALESCE ( name,'Total'::text) as name,
sum(points) as points
FROM animals
GROUP BY category, color, name
),
data_evolutions as
(
select grouping(d.category, d.color, d.name) as GR_ALL,
d.category,
d.color,
d.name,
sum(d.points) as points
from data_grouped d
group by rollup(d.category, d.color, d.name)
order by category, color, name
)
select
COALESCE (d.category, 'Total'::text) as "CATEGORY",
COALESCE (d.color, 'Total'::text) as "COLOR",
COALESCE (d.name, 'Total'::text) as "NAME",
points
from data_evolutions d
order by
CASE WHEN category IS NULL THEN 1 ELSE 0 END, category,
CASE WHEN color IS NULL THEN 1 ELSE 0 END, color,
CASE WHEN name IS NULL THEN 1 ELSE 0 END, points desc
但是我仍然得到错误的命令。
动物是按名称而不是按总和排序的。 我应该如何更改查询以获取每个级别中点的总和的降序顺序?
我需要正确的总和,并按总计和小计排序。