0

我可以毫无问题地在mysql中运行它

SELECT 
    DATE_FORMAT(trans_date, '%Y-%m') month, 
    COUNTRY, COALESCE(COUNT(*), 0) trans_count,
    COALESCE(SUM(CASE WHEN state ='approved' THEN 1 END), 0) approved_count,
    COALESCE(SUM(amount), 0) trans_total_amount,
   COALESCE(SUM(CASE WHEN state ='approved' THEN amount END), 0) approved_total_amount
FROM 
    Transactions
GROUP BY 
    month, COUNTRY
ORDER BY 
    month;

但是相同的查询不在 Orcale 中运行,我不能使用GROUP BYusing 聚合别名,并且我不能在不使用GROUP BY.

我可以通过子查询调用子查询或使用 CTE,但这太乏味了。

什么是问题类型的好查询?

4

2 回答 2

1

如另一个答案中所述,您不能在其中添加别名,GROUP BY但可以在ORDER BY. 还有,DATE_FORMAT就是MySql函数。它TO_CHAR在甲骨文中。

因此,您的最终查询应如下所示:

SELECT
    TO_CHAR(TRANS_DATE, 'YYYY-MM') AS MONTH,
    COUNTRY,
    COUNT(*) AS TRANS_COUNT,
    SUM(CASE WHEN STATE = 'approved'  THEN 1 ELSE 0 END) AS APPROVED_COUNT,
    SUM(AMOUNT) AS TRANS_TOTAL_AMOUNT,
    SUM(CASE WHEN STATE = 'approved' THEN AMOUNT ELSE 0 END) AS APPROVED_TOTAL_AMOUNT
FROM TRANSACTIONS
GROUP BY TO_CHAR(TRANS_DATE, 'YYYY-MM'), COUNTRY
ORDER BY MONTH;
于 2020-03-31T02:33:22.637 回答
0

Oracle 不支持GROUP BY. 此外,COALESCE()在这种情况下是不必要的:

SELECT DATE_FORMAT(trans_date, '%Y-%m') as month, COUNTRY,
       COUNT(*) as trans_count,
       SUM(CASE WHEN state ='approved' THEN 1 ELSE 0 END) as approved_count,
       SUM(amount) as trans_total_amount,
       SUM(CASE WHEN state = 'approved' THEN amount ELSE 0 END) as  approved_total_amount
FROM Transactions
GROUP BY DATE_FORMAT(trans_date, '%Y-%m'), COUNTRY
ORDER BY month;
于 2020-03-31T01:47:59.200 回答