如何将CASE查询与另一个JOIN查询相结合

时间:2017-09-22 10:54:11

标签: mysql mysqli

您好我有以下查询:

SELECT x.id , x.amount , x.amount as paid_amount , SUM(y.bal) as total, x.reciept_no
  FROM (SELECT *, paid bal 
          FROM challan_1 ) x 
  JOIN (SELECT *, amount bal 
          FROM challan_1 ) y
    ON y.id <= x.id 
 GROUP BY x.id 
HAVING total <= '500'
它工作得很好。输出如

enter image description here

然后我做了一个新的查询,如下所示

SELECT *, (CASE WHEN 500-sum(amount) >= 0
                THEN '0'
                ELSE 500-SUM(paid) END) as pending_amt 
  FROM challan_1

输出是 enter image description here

此查询返回一个Pending Amount,因此我需要将两个查询组合在一起,以便如何组合这两个查询。 我在第一次查询中需要此待处理金额。 这是我的SQL Fiddle

我需要像这样。用户有500种货币并且有3种付款因此对于那种情况输出应该是这样的。 enter image description here 其中100是待处理金额,200来自用户价值。借记录。

2 个答案:

答案 0 :(得分:0)

将子查询添加为另一个连接。

SELECT x.id , x.amount , x.amount as paid_amount , SUM(y.bal) as total, x.reciept_no, p.pending_amt
  FROM (SELECT *, paid bal 
          FROM challan_1 ) x 
  JOIN (SELECT *, amount bal 
          FROM challan_1 ) y
    ON y.id <= x.id 
  CROSS JOIN (SELECT CASE WHEN SUM(amount) <= 500
                          THEN '0'
                          ELSE 500 - SUM(paid)
                     END AS pending_amt
              FROM challan_1) AS p
 GROUP BY x.id 
HAVING total <= '500'

答案 1 :(得分:0)

我不完全明白,但这是我对此的看法。 500可用。有记录显示付款。奇怪到甚至超过500,所以我认为如果有更多的钱,这些是可能的费用/支付。我停在付款超过500的地方。

SELECT 
  challan.*, 
  SUM(addup.amount) as total_amount, 
  sum(addup.paid) as total_paid,
  sum(addup.amount) - sum(addup.paid) as total_pending,
  sum(addup.amount) <= sum(addup.paid) as status
FROM challan_1 challan
JOIN challan_1 addup ON addup.id <= challan.id 
GROUP BY challan.id
HAVING sum(addup.paid) <= 500
ORDER BY challan.id;

如果您想要显示更多记录,即删除HAVING条款,您需要另一个待处理金额的公式,因为可能的最高付款金额为500:

SELECT 
  challan.*, 
  SUM(addup.amount) as total_amount, 
  sum(addup.paid) as total_paid,
  sum(addup.amount) - least(500, sum(addup.paid)) as total_pending,
  sum(addup.amount) <= least(500, sum(addup.paid)) as status
FROM challan_1 challan
JOIN challan_1 addup ON addup.id <= challan.id 
GROUP BY challan.id
ORDER BY challan.id;