如何发送查询?

时间:2020-03-12 02:01:40

标签: mysql sql

如果我发送以下查询:

SELECT * FROM (
    SELECT COUNT(*) as total, SUM(ABS(AMOUNT)) AS Total_Amount 
    FROM success_log  
    WHERE TRANSACTION = 'success' ) t1 
CROSS JOIN  (
    SELECT COUNT(*) as success_total,  SUM((AMOUNT))  AS success_Amount 
    FROM success_log  WHERE 
    TRANSACTION = 'success' ) t2
CROSS JOIN  (
    SELECT COUNT(*) as Fail_total, SUM(ABS(AMOUNT)) AS Fail_Amount 
    FROM success_log  
    WHERE TRANSACTION = 'cancle') t3

结果:

enter image description here

但是我想要结果:

enter image description here

如何发送查询?

模式是 enter image description here

2 个答案:

答案 0 :(得分:1)

以下方法应该起作用:

SELECT total,
       Total_amount,
       (total - Fail_total) AS success_total,
       (Total_amount - Fail_amount) AS success_Amount,
       Fail_total,
       Fail_amount
FROM (
    SELECT COUNT(*) as total,
           SUM(ABS(AMOUNT)) AS Total_Amount
    FROM success_log
    WHERE TRANSACTION = 'success'
) t1 
CROSS JOIN (
    SELECT COUNT(*) as Fail_total, 
           SUM(ABS(AMOUNT)) AS Fail_Amount 
    FROM success_log
    WHERE TRANSACTION = 'cancle'
) t3

仅说明一下,您的第二个交叉联接t2没有返回正确的结果,因此我使用了t1和t3的原始列,并通过减去它们的差来添加了另外两列以显示成功总数和金额。

答案 1 :(得分:0)

您必须在total_amount计算选择查询中删除 此处 条件。

希望这个有用...

SELECT
  total,Total_Amount,success_total,success_Amount,Fail_total,Fail_Amount
FROM
  ( 
    SELECT
      COUNT() as total
      , SUM(ABS(AMOUNT)) AS Total_Amount 
    FROM
      success_log 
  ) t1 
  CROSS JOIN ( 
    SELECT
      COUNT() as success_total
      , SUM((AMOUNT)) AS success_Amount 
    FROM
      success_log 
    WHERE
      TRANSACTION = 'success'
  ) t2 
  CROSS JOIN ( 
    SELECT
      COUNT(*) as Fail_total
      , SUM(ABS(AMOUNT)) AS Fail_Amount 
    FROM
      success_log 
    WHERE
      TRANSACTION = 'cancel'
  ) t3