sql—如何通过查询行中的特定字段来计算成本

1cosmwyk  于 2021-05-27  发布在  Spark
关注(0)|答案(4)|浏览(373)

如果我有以下数据

Cust No.  |  Action       | Val
----------| --------------| ----
10        | Checked out   | 1.0
10        | PAID          | 40.0
10        | Checked In    | 1.0
15        | Flew Away     | 2.0
15        | PAID          | 100.00
15        | Came back     | 1.0
20        | PAID          | 150.00
30        | Checked In    | 1.0
30        | PAID          | 50.00
30        | PAID          | 10.00

我怎样才能拿到票 SUM 只有 PAID 每个客户的价值观 Checked In 进入
即。

Cust No.  |  Total Paid       
----------| --------------
30        | 60.00
10        | 40.00
yfwxisqw

yfwxisqw1#

我没有Spark测试,但一种方法应该是使用 HAVING 找出组中是否有“签入”行;

SELECT `Cust No`, SUM(CASE WHEN Action='PAID' THEN val END) paid 
FROM mytable 
GROUP BY `Cust No` 
HAVING MAX(CASE WHEN Action='Checked In' THEN 1 ELSE 0 END) > 0

+---------+------+
| Cust No | paid |
+---------+------+
|      10 |   40 |
|      30 |   60 |
+---------+------+

另一种是使用 WHERE 先求群,然后求和;

SELECT `Cust No`, SUM(val) paid 
FROM mytable 
WHERE action='PAID' AND `Cust No` IN (
  SELECT `Cust No` FROM mytable WHERE action='Checked In'
) 
GROUP BY `Cust No`
watbbzwu

watbbzwu2#

使用 CASE 条件以及 SUM 喜欢

sum(case when Action = 'paid' then val end)

如果使用外部查询稍微调整一下查询,比如

select customer_number, PaymentDone
from (
select customer_number, 
sum(case when Action = 'paid' then val end) as PaymentDone,
group_concat(Action ORDER BY Action asc) as Action_List 
from tbl1
group by customer_number) xxx
where Action_List like 'Checked In%';
56lgkhnf

56lgkhnf3#

这应该管用

select customer_number, sum(value) as total_paid 
from table_name where action = 'PAID' group by customer_number;
9nvpjoqh

9nvpjoqh4#

这应该起作用:

select customer.customer_number, sum(value) as total_paid  from customers
    left join
    (
      select customer_number from users where action = 'Checked In' group by customer_number
    )checkins on checkins.customer_number = customers.customer_number 
    where checkins.customer_number is not null and customers.action = 'PAID'
    group by customers.customer_number

相关问题