[英]How to order id's using subtotal from another column in PostgreSQL
I have a table returned by a select query.我有一个 select 查询返回的表。 Example:
例子:
id | day | count |
-- | ------ | ----- |
1 | 71 | 3 |
1 | 70 | 2 |
1 |Subtotal| 5 |
2 | 70 | 5 |
2 | 71 | 2 |
2 | 69 | 2 |
2 |Subtotal| 9 |
3 | 69 | 1 |
3 | 70 | 1 |
3 |Subtotal| 2 |
the day column contains text values (so varchar) day 列包含文本值(所以 varchar)
subtotal is the sum of the counts for an id (eg id 2 has subtotal of 5 + 2 + 2 = 9)小计是 id 的计数总和(例如,id 2 的小计为 5 + 2 + 2 = 9)
I now want to order this table so the id's with the lowest subtotal count come first, and then ordered by day with subtotal at the end (like before)我现在想订购这张桌子,所以小计最少的 id 排在第一位,然后按天排序,小计在最后(像以前一样)
Expected output:预期 output:
id | day | count |
-- | ------ | ----- |
3 | 69 | 1 |
3 | 70 | 1 |
3 |Subtotal| 2 |
1 | 70 | 2 |
1 | 71 | 3 |
1 |Subtotal| 5 |
2 | 69 | 2 |
2 | 70 | 5 |
2 | 71 | 2 |
2 |Subtotal| 9 |
I can't figure out how to order based on subtotal only?我不知道如何仅根据小计订购?
i've tried multiple order by (eg: ORDER BY day = 'Subtotal' & a mix of others) and using window functions but none are helping.我已经尝试过多次订购(例如:ORDER BY day = 'Subtotal' & a mix of others)并使用 window 函数,但没有任何帮助。 Cheers !
干杯!
Not sure if it's directly applicable to your source query (since you haven't included it) however the ordering you require on the sample data can be done with:不确定它是否直接适用于您的源查询(因为您没有包含它)但是您需要对示例数据进行排序可以通过以下方式完成:
order by Max(count) over(partition by id), day
Note - ordering by day works with your sample data but as it's a string it will not honour numeric ordering, this should really be ordered by the source of the numerical value - again since we don't have your actual query I can't suggest anything more applicable but I'm sure you can substitute the correct column/expression.注意 - 按天排序适用于您的示例数据,但由于它是一个字符串,因此它不支持数字排序,这实际上应该按数值的来源排序 - 再次,因为我们没有您的实际查询,我无法建议任何更适用的东西,但我相信您可以替换正确的列/表达式。
I just crated table with 3 columns and tried to reproduce your expected result.我只是用 3 列装箱并试图重现您的预期结果。 I assume that there might be a problem ordering by day, subtotal would be always on top, but it seems as working solution.
我认为按天排序可能会出现问题,小计总是排在首位,但这似乎是可行的解决方案。
create table test
(
id int,
day varchar(15),
count int
)
insert into test
values
(1,'71',3),
(1,'70',2),
(2,'70',5),
(2,'71',2),
(2,'69',2),
(3,'69',1),
(3,'70',1)
select id, day, count
from
(
select id, day, sum(count) as count
from test
group by id, rollup(day)
) as t
order by Max(count) over(partition by id), day
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.