Sql 按总和排序,但不聚合结果集(按小计排序)

Sql 按总和排序,但不聚合结果集(按小计排序),sql,group-by,sql-order-by,h2,Sql,Group By,Sql Order By,H2,我有下表 +--------+----------+--------+ | STORE | PRODUCT | AMOUNT | +--------+----------+--------+ | store1 | product1 | 100 | | store1 | product2 | 90 | | store2 | product2 | 95 | | store2 | product1 | 90 | | store3 | product1 | 120

我有下表

+--------+----------+--------+
| STORE  | PRODUCT  | AMOUNT |
+--------+----------+--------+
| store1 | product1 |    100 |
| store1 | product2 |     90 |
| store2 | product2 |     95 |
| store2 | product1 |     90 |
| store3 | product1 |    120 |
+--------+----------+--------+
问题是,我想按每家商店的总金额来订购这张桌子。在本例中,store1有190个,store2有185个,store3有120个。因此,在这个例子中,订购是允许的,我也希望按每个产品的数量订购,但不希望将其超出“存储”的范围,也不希望按分组,因为我需要显示所有行

如何在H2数据库中实现这种排序?我可以欣赏其他数据库,但H2是我最关心的问题


顺便说一句,性能是这里的一个大问题…

在大多数数据库中,您将使用窗口功能。H2不支持它们。因此,您需要执行显式联接:

select t.*
from table t join
     (select store, sum(amount) as totalamount
      from table t
      group by store
     ) ts
     on t.store = ts.store
order by ts.totalamount desc, ts.store;

请注意,
store
位于
orderby
中。这将处理两个分数合计相同的情况。每个商店的所有行仍将在一起。

这是处理此问题的最佳方法吗?我想避免连接,因为性能是一个大问题。我认为您唯一的选择是显式连接(如答案所示)或使用相关子查询的隐式连接。