2
我有一個客戶表如下:需要一個PostgreSQL的查詢分組和順序
customername, ordername, amount
=============================
bob, book, 20
bob, computer, 40
steve,hat, 15
bill, book, 12
bill, computer, 3
steve, pencil, 10
bill, pen, 2
我想運行一個查詢,得到以下結果:
customername, ordername, amount
=============================
bob, computer, 40
bob, book, 20
bob, ~total~, 60
steve, hat, 15
steve, pencil, 10
steve, ~total~,25
bill, book, 12
bill, computer, 3
bill, pen, 2
bill, ~total~, 17
我想要的金額每個客戶從最大值到最小值以及一個新的訂單名稱都被定義爲「總共〜」(必須始終是每個客戶的最後一行),並將結果作爲同一客戶的所有金額的總和。 因此,在上面的例子中,bob應該是總數= 60以來的第一個,第二個(總數= 25)和第三個(總數= 17)。
我喜歡「幻影列進行排序」的想法。我正在構建一個花哨的ORDER BY,它涉及到與'〜total〜''的比較,但是你的方式更加乾淨 - 即使有人下了一個名爲''total〜''的命令,它也能工作。 – 2010-08-31 04:25:26
感謝您的解決方案。但是,它仍然沒有按降序排列金額列。 – Rowshan 2010-08-31 05:09:07
將x.amount DESC添加到最後一行(ORDER BY x.customername,x.sort,x.amount DESC)中。 再次感謝 – Rowshan 2010-08-31 05:12:43