次の列を持つテーブルがあるとします。
- タイプ
- デパートメント
- サプライヤー
- 注文
- 合計
そして、このデータをクエリして、最初に 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;
このデータにクエリを実行して、最初に TYPE でグループ化し、次に DEPARTMENT でグループ化した順序付けされた結果を取得します。注文は注文数です。次に、次のクエリがうまく機能します(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;
ただし、注文した結果が必要な場合は同じパターンに従います。最初に TYPE でグループ化し、次に DEPARTMENT でグループ化し、次に SUPPLIER でグループ化します。順序は注文数です。次に、次のクエリは機能しません( 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;
上記のクエリの結果は次のようになります。
一方、私は次のことを望んでいます:
どこが間違っていますか?