假设我有一个包含以下列的表格:
- 类型
- 部
- 供应商
- 命令
- 全部的
我想查询这些数据,以便得到有序的结果,首先按 TYPE 分组。订单是订单数量。然后以下查询对我来说很有效(http://sqlfiddle.com/#!15/78cc1/1):
WITH company_sales(type, department, supplier, order_number, total) AS (
VALUES
('Edibles' , 'Department-1', 'Supplier-1' , 'ORDER-1' , 10)
, ('Edibles' , 'Department-1', 'Supplier-2' , 'ORDER-2' , 20)
, ('Edibles' , 'Department-1', 'Supplier-3' , 'ORDER-3' , 30)
, ('Edibles' , 'Department-1', 'Supplier-4' , 'ORDER-4' , 40)
, ('Edibles' , 'Department-2', 'Supplier-5' , 'ORDER-5' , 50)
, ('Edibles' , 'Department-2', 'Supplier-6' , 'ORDER-6' , 60)
, ('Edibles' , 'Department-3', 'Supplier-7' , 'ORDER-7' , 70)
, ('Edibles' , 'Department-3', 'Supplier-8' , 'ORDER-8' , 80)
, ('Edibles' , 'Department-3', 'Supplier-9' , 'ORDER-9' , 90)
, ('Edibles' , 'Department-3', 'Supplier-9' , 'ORDER-10', 100)
, ('Edibles' , 'Department-4', 'Supplier-10', 'ORDER-11', 110)
, ('Non-Edibles', 'Department-2', 'Supplier-11', 'ORDER-12', 1000)
, ('Non-Edibles', 'Department-3', 'Supplier-12', 'ORDER-13', 1010)
, ('Non-Edibles', 'Department-3', 'Supplier-13', 'ORDER-14', 1020)
, ('Non-Edibles', 'Department-3', 'Supplier-14', 'ORDER-15', 1030)
, ('Non-Edibles', 'Department-3', 'Supplier-14', 'ORDER-16', 1040)
, ('Non-Edibles', 'Department-4', 'Supplier-15', 'ORDER-17', 1050)
)
SELECT cs.type,
count(*) sum_total_count,
sum(total) sum_grand_total
FROM company_sales cs
GROUP BY cs.type
ORDER BY Sum(Count(*)) OVER (partition BY cs.type) DESC,
cs.type ASC;
如果我想查询这些数据以获得有序的结果,首先按类型分组,然后按部门分组。订单是订单数量。然后下面的查询对我很有效(http://sqlfiddle.com/#!15/78cc1/2):
WITH company_sales(type, department, supplier, order_number, total) AS ( ...)
SELECT cs.type,
cs.department,
count(*) sum_total_count,
sum(total) sum_grand_total
FROM company_sales cs
GROUP BY cs.type,
cs.department
ORDER BY Sum(Count(*)) OVER (partition BY cs.type) DESC,
Sum(Count(*)) OVER (partition BY cs.type, cs.department) DESC,
cs.type ASC,
cs.department ASC;
但是,当我想要订购结果时遵循相同的模式,首先按类型分组,然后按部门分组,然后按供应商分组,顺序是订单数。然后以下查询对我不起作用(http://sqlfiddle.com/#!15/78cc1/3):
WITH company_sales(type, department, supplier, order_number, total) AS (...)
SELECT cs.type,
cs.department,
cs.supplier,
count(*) sum_total_count,
sum(total) sum_grand_total
FROM company_sales cs
GROUP BY cs.type,
cs.department,
cs.supplier
ORDER BY Sum(Count(*)) OVER (partition BY cs.type) DESC,
Sum(Count(*)) OVER (partition BY cs.type, cs.department) DESC,
Sum(Count(*)) OVER (partition BY cs.type, cs.department, cs.supplier) DESC,
cs.type ASC,
cs.department ASC,
cs.supplier ASC;
上述查询结果如下:
鉴于,我希望以下内容:
我哪里错了?