我有一个名为“付款”的表格,其中包含以下数据
+---------------------------------------+
| status | currency | amount |
+---------------------------------------+
| ------------------------------------- |
| paid | USD | 10 |
| pending | USD | 20 |
| processing | GBP | 30 |
| paid | GBP | 40 |
| paid | EUR | 50 |
| pending | USD | 60 |
| processing | EUR | 70 |
+----------------------------------------+
我需要编写一个查询,该查询将为我提供以下格式的结果
Paid : 3
Processing: 2
Pending: 2
我可以使用以下查询做到这一点
select status, count(status)
from payments
group by status;
现在,我还需要知道这些高级组中每个按货币分组的金额总和。例如,
对于具有3条记录的“已付款”状态,我还需要
USD: 10
GBP: 40
EUR: 50
我该怎么做?
答案 0 :(得分:2)
select status, currency, sum(amount)
from payments
group by status, currency;
答案 1 :(得分:0)
我想你想要
select status, currency, count(*), sum(amount)
from payments
group by grouping sets ( (status, currency), (status) )
答案 2 :(得分:0)
第一个查询应类似于:
SELECT INITCAP(STATUS) || ' : ' || COUNT(*) AS OUTPUT_TEXT
FROM PAYMENTS
GROUP BY STATUS
ORDER BY CASE STATUS
WHEN 'paid' THEN 1
WHEN 'processing' THEN 2
WHEN 'pending' THEN 3
ELSE 4
END
第二个查询应该是
SELECT CURRENCY || ': ' || SUM(CURRENCY) AS OUTPUT_TEXT
FROM PAYMENTS
GROUP BY CURRENCY
ORDER BY CASE CURRENCY
WHEN 'USD' THEN 1
WHEN 'GBP' THEN 2
WHEN 'EUR' THEN 3
ELSE 4
END
好运。