基于列值

时间:2017-08-06 16:04:29

标签: mysql sql

我有一张表transactions

client_id   Amount   payment ref   contract type
1           300      MTV           1
1           300      MTV           1
1           300      MTV           1
1           150      ML            1
2           150      ML            2
2           150      ML            2
2           150      ML            2
2           150      ML            2

如果客户在合同1上,那么他们的总付款应为3 x MTV(300)和3 x ML(150)。如果他们在合同2上,那么他们支付6 x ML(150)。

我试图找出如何根据合约类型获取每个客户的剩余付款总数。例如client_id = 1:

client_id   type   Total Paid   Payments remaining
1           MTV    900          0
1           ML     150          2

我可以使用这个来完成前三列:

SELECT   `client_id`,
         `payment ref` AS `type`,
         SUM(`Amount`) as `Total Paid` 
FROM     transactions
WHERE    client_id = 1
GROUP BY type;

如何添加剩余付款列?

CASE WHEN `contract type` = 1 THEN (3 - COUNT(MTV)... ? 

3 个答案:

答案 0 :(得分:2)

你非常接近,GROUP BY子句存在问题,不包括client_id和付款参考:

SELECT 
client_id, 
payment ref AS type, 
SUM(Amount) as 'Total Paid',
CASE 
WHEN contract type = 1 THEN (3 - COUNT(*))
WHEN contract type = 2 THEN (6 -  COUNT(*))
END as 'Payments remaining'
FROM transactions 
WHERE client_id = 1 
GROUP BY client_id, 
payment ref;

答案 1 :(得分:1)

可以使用case when when by group

FailedPreconditionError: Attempting to use uninitialized value Variable_344
     [[Node: Variable_344/read = Identity[T=DT_FLOAT, _class=["loc:@Variable_344"], _device="/job:localhost/replica:0/task:0/cpu:0"](Variable_344)]]

答案 2 :(得分:1)

尝试以下查询

    select *
       ,case contract_type 
            when 1 then 3-paidCount  
            when 2 then 6-paidCount  
       End               
    from (
        select client_id  , payment_ref ,  contract_type,sum(Amount)TotalPaid ,count(*) paidCount
        FROM     transactions
        group by client_id  , payment_ref ,  contract_type
      ) t