这是我在sql中的表
CREATE TABLE Customer (ID char(50), Customer_FName char(50), Customer_Lname char(50));
CREATE TABLE Buying (Customer_ID char(50), Product_ID char(50), Order_Time char(50));
CREATE TABLE Product (ID char(50), Name char(50), Address char(50));
我试图找到2017年或更早购买产品的所有客户,并列出该客户的ID,姓名
select *
from Customer
INNER JOIN Buying
Buying.Customer_ID = Customer.ID
where Buying.Order_Time <= '2017-12-31';
但是我有一个错误
ORA-009005(缺少关键字)
答案 0 :(得分:2)
select * from Customer INNER JOIN Buying on Buying.Customer_ID = Customer.ID where extract(year from date Buying.Order_Time) <= 2017;
购买后“打开”是缺少的关键字
答案 1 :(得分:0)
我想正在写:
select *
from Customer c inner join
Buying b
on b.Customer_ID = c.ID
where b.Order_Time < date '2018-01-01';
on
和date
都是必需的。
但是,在日期之前,每次购买都会返回一行。如果只需要一行,请使用exists
:
select c.*
from Customer c
where exists (select 1
from Buying b
where b.Customer_ID = c.ID and
b.Order_Time < date '2018-01-01'
);
答案 2 :(得分:0)
您缺少了ON
关键字,并且存在一个额外的问题,即在Oracle中,日期始终具有年,月,日,小时,分钟和秒的组成部分,并且(假设NLS_DATE_FORMAT
会话参数允许从字符串到日期的有效转换),那么'2017-12-31'
将转换为2017-12-31T00:00:00
,并且您的查询将不会选择2017-12-31T00:00:01
和2017-12-31T23:59:59
之间的值。>
要解决此问题:
SELECT *
FROM Customer c
INNER JOIN Buying b
ON ( b.Customer_ID = c.ID )
WHERE b.Order_Time < DATE '2018-01-01';
或
SELECT *
FROM Customer c
INNER JOIN Buying b
ON ( b.Customer_ID = c.ID )
WHERE b.Order_Time < ADD_MONTHS( TRUNC( TO_DATE( 2017, 'YYYY' ), 'YY' ), 12 );