如何在sql中进行分组和求和

jucafojl  于 2021-07-24  发布在  Java
关注(0)|答案(5)|浏览(393)

我有下面这样的表格,我想从中抽取 product=a ```
customer product score
A a 10
A b 20
A c 30
B b 10
B c 20
C a 30
C c 40

然后,我想 `sum` 每个客户的得分。

customer product score
A a 10
A b 20
A c 30
C a 30
C c 40

所以我想要的结果是这样的:有什么方法可以达到这个目的吗?

customer score
A 60
C 70

我的工作如下。我想知道下一步

SELECT t1.customer, t1.product, t1.score
FROM yourTable t1
WHERE EXISTS (SELECT 1
FROM yourTable t2
WHERE t2.customer = t1.customer
AND t2.product = 'a');

谢谢
slmsl1lt

slmsl1lt1#

您需要一个聚合(groupby)和一个sum(t1.score)

SELECT t1.customer, sum(t1.score) as summed_score
  FROM yourTable t1
WHERE EXISTS (SELECT 1 
                FROM yourTable t2 
               WHERE t2.customer = t1.customer 
                 AND t2.product = 'a')
GROUP BY t1.customer
vs3odd8k

vs3odd8k2#

一种选择是使用 HAVING 带聚合的子句:

SELECT customer, SUM(score) AS score
  FROM t
 GROUP BY customer 
HAVING SUM(CASE WHEN product = 'a' THEN 1 END)>0

演示

yks3o0rb

yks3o0rb3#

这只是一个简单的聚合

select customer, sum(score)
from tablename t where exists (select 1 from tablename t1 where t.customer=t2.customer and t1.product='a')
group by customer
ipakzgxi

ipakzgxi4#

现在只需使用group by()&sum()

SELECT t1.customer, sum(t1.score) 
FROM  my_table t1 
WHERE EXISTS (SELECT 1 FROM my_table t2 WHERE t2.customer = t1.customer AND t2.product = 'a') 
group by t1.customer;

SELECT t1.customer, sum(t1.score) 
FROM  my_table t1 
WHERE EXISTS (SELECT 1 FROM my_table t2 WHERE t2.customer = t1.customer AND t2.product = 'a') 
group by t1.customer 
order by t1.customer;
yhxst69z

yhxst69z5#

请使用下面的查询,只需检查同一表的子查询中product='a'的customer列

select customer, sum(score) as score from table_name where customer in
(select customer from table_name where product = 'a')
group by customer;

相关问题