查询多个表和行/列

时间:2016-07-15 13:48:21

标签: sql oracle oracle11g dml

我遇到了使用Oracle 11g快速版设置的SQL数据库的问题。我希望能够运行SELECT查询,其中对于每个客户,我想显示客户的号码以及所有客户的信用交易(具有“C”类型的交易)的总和金额为具有开放的帐户状态。

问题...我已经查看了不同类型的Query命令,我完全不知道如何用最简单的术语格式化这个命令。任何帮助,将不胜感激。这是我的表格格式:

CREATE TABLE Customer_DML

  CustomerNumber CHAR(12) CONSTRAINT customer_pk PRIMARY KEY, 

  SSN CHAR(9) CONSTRAINT customer_uq_ssn UNIQUE,

  FirstName VARCHAR2(25) CONSTRAINT customer_nn_fname NOT NULL,

  LastName VARCHAR2(25) CONSTRAINT customer_nn_lname NOT NULL,

  Telephone CHAR(10),

  DateOfBirth DATE
);



CREATE TABLE Account_DML (

  AccountNumber CHAR(15) CONSTRAINT account_pk PRIMARY KEY,

  Type CHAR(1) CONSTRAINT account_ck_type CHECK (Type IN ('S','C')),

  DateCreated DATE DEFAULT SYSDATE CONSTRAINT account_nn_datecreated NOT NULL,

  Status VARCHAR2(10) CONSTRAINT account_nn_status NOT NULL,

  Customer CHAR(12) CONSTRAINT account_fk_customer REFERENCES 
Customer_DML(CustomerNumber)

ON DELETE CASCADE
);


CREATE TABLE Transaction_DML (

  TransactionNumber CHAR(15) CONSTRAINT transaction_pk PRIMARY KEY,

  Type CHAR(1) CONSTRAINT transaction_ck_type CHECK (Type IN ('D','C')),

  Amount Number(10,2) CONSTRAINT transaction_nn_amount NOT NULL,

  Account CHAR(15) CONSTRAINT transaction_fk_account REFERENCES Account_DML(AccountNumber)

ON DELETE SET NULL
);

到目前为止我所拥有的是:

SELECT c.CustomerNumber,
t.SUM(Amount) AS SumAmt
FROM Customer_DML c, Account_DML a
ON c.CustomerNumber = a.Customer
JOIN Transaction_DML t
ON a.Customer = a.AccountNumber

但我觉得我真的不喜欢这个。

任何提示或解决方案将不胜感激。如果您需要更多信息,我很乐意尽我所能。

1 个答案:

答案 0 :(得分:0)

简单规则:从不FROM子句中使用逗号。 始终使用正确的JOIN语法。

你也错过了GROUP BY,所以我认为你的意思是:

SELECT a.Customer as CustomerNumber, SUM(t.Amount) AS SumAmt
FROM Account_DML a 
JOIN Transaction_DML t
     ON t.Account = a.AccountNumber
GROUP BY a.Customer;

您不需要加入customer表,因为Account表具有聚合所需的客户编号。