[英]How to order by after rollup and not split grouping?
I use rollup and i want to order by best year (by profit not in alphabetical order) and not split groups of years. 我使用汇总,我想按最佳年份排序(按利润排序,而不是按字母顺序排序),而不是按年份分组。
Each year order by best product (by profit not in alphabetical order) and not split etc. 每年按最佳产品排序(按利润而不是按字母顺序排列),并且不拆分等。
I want something like this: 我想要这样的东西:
But i have only this: 但是我只有这个:
DROP TABLE IF EXISTS abc;
CREATE TABLE abc(year text,
country text, product text, profit integer);
INSERT INTO abc VALUES ('2016', 'USA', 'Phone', 3000);
INSERT INTO abc VALUES ('2016', 'USA', 'TV', 1000);
INSERT INTO abc VALUES ('2016', 'UK', 'TV', 2000);
INSERT INTO abc VALUES ('2016', 'UK', 'Phone', 1000);
INSERT INTO abc VALUES ('2015', 'USA', 'TV', 1500);
INSERT INTO abc VALUES ('2015', 'USA', 'Phone', 1000);
INSERT INTO abc VALUES ('2015', 'UK', 'Phone', 900);
INSERT INTO abc VALUES ('2015', 'UK', 'TV', 600);
INSERT INTO abc VALUES ('2014', 'USA', 'Phone', 1500);
INSERT INTO abc VALUES ('2014', 'USA', 'TV', 1000);
INSERT INTO abc VALUES ('2014', 'UK', 'Phone', 1500);
INSERT INTO abc VALUES ('2014', 'UK', 'TV', 2000);
with data as
(
SELECT year, country, product, profit from abc
)
select l.year as year, l.country as country, l.product as product,
sum(l.profit) as profit
from data l
group by rollup(year, country, product)
ORDER BY
CASE WHEN year IS NULL THEN 1 ELSE 0 END, year
When i order by sum(l.profit) it split years. 当我按总和(l.profit)订购时,它会分开几年。
Add more to the order by clause: 向order by子句添加更多内容:
DROP TABLE IF EXISTS abc;
CREATE TABLE abc(year text,
country text, product text, profit integer);
INSERT INTO abc VALUES ('2016', 'USA', 'Phone', 3000);
INSERT INTO abc VALUES ('2016', 'USA', 'TV', 1000);
INSERT INTO abc VALUES ('2016', 'UK', 'TV', 2000);
INSERT INTO abc VALUES ('2016', 'UK', 'Phone', 1000);
INSERT INTO abc VALUES ('2015', 'USA', 'TV', 1500);
INSERT INTO abc VALUES ('2015', 'USA', 'Phone', 1000);
INSERT INTO abc VALUES ('2015', 'UK', 'Phone', 900);
INSERT INTO abc VALUES ('2015', 'UK', 'TV', 600);
INSERT INTO abc VALUES ('2014', 'USA', 'Phone', 1500);
INSERT INTO abc VALUES ('2014', 'USA', 'TV', 1000);
INSERT INTO abc VALUES ('2014', 'UK', 'Phone', 1500);
INSERT INTO abc VALUES ('2014', 'UK', 'TV', 2000);
with data as
(
SELECT year, country, product, profit from abc
)
select l.year as year, l.country as country, l.product as product,
sum(l.profit) as profit
from data l
group by rollup(year, country, product)
ORDER BY
CASE WHEN year IS NULL THEN 1 ELSE 0 END,
year,
case when product is NULL THEN 1 else 0 end,
profit desc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.