在sql中使用聚合函数进行SELECT

时间:2014-05-30 08:44:34

标签: sql oracle select

我有两张桌子:

CREATE TABLE cheque
  (
    ch_id          NUMBER NOT NULL ,
    ch_price       VARCHAR2 (100) ,
    ch_customer    NUMBER NOT NULL
  ) ;
ALTER TABLE cheque ADD CONSTRAINT check_PK PRIMARY KEY ( ch_id ) ;

CREATE TABLE customer
  (
    cus_id      NUMBER NOT NULL ,
    cus_name    VARCHAR2 (100) ,
  ) ;
ALTER TABLE customer ADD CONSTRAINT customer_PK PRIMARY KEY ( cus_id ) ;

ALTER TABLE cheque ADD CONSTRAINT check_customer_FK FOREIGN KEY ( ch_customer ) REFERENCES customer ( cus_id );

如何获得每个客户的价格总和?例如,如果我有一个客户约翰和3检查他的ch_price 10,20和30的记录,我将得到约翰 - 60。

我尝试了这个,但它不起作用:

Select cus_name, sum(ch_price) 
from customer, cheque
where cheque_customer=cus_id;

1 个答案:

答案 0 :(得分:3)

使用GROUP BY

Select cus_name, sum(ch_price) as Total
from customer, cheque
where cheque_customer=cus_id
group by cus_name