SQL DELETE使用DATE

时间:2013-08-31 09:22:00

标签: sql oracle date sql-delete

    CUSTOMER(CustID, CustName)
    Sale(SaleNo, StockNo, CustNo, SaleDate)

如何删除自2009年以来未购买任何商品的客户?

我可以使用减号

来获取CustID
    SELECT CustID FROM CUSTOMER
    WHERE SaleDate <= to_date('31-12-09', 'DD-MM-YY')
    MINUS
    SELECT CustID FROM CUSTOMER
    WHERE SaleDate > to_date('31-12-09', 'DD-MM-YY');

但我不知道如何在单个查询中执行删除。

任何建议都将受到赞赏

3 个答案:

答案 0 :(得分:3)

delete from CUSTOMER c
inner join Sale S 
on C.CustID=S.CustNo
where max(SaleDate)<='31-12-09'

答案 1 :(得分:2)

您没有指定您的DBMS,虽然我怀疑它是Oracle,因为使用了MINUSto_date()

无论如何,以下内容应适用于Oracle(以及任何符合ANSI标准的DBMS)

delete from customer
where not exists (select 1 
                  from sale
                  where sale.custId = customer.CustNo
                    and sale.saledate >= date '2009-01-01')

答案 2 :(得分:0)

在SQL Server中

DELETE FROM Customer
WHERE CustID IN ( SELECT CustNo FROM Sale 
                  GROUP BY CustNo
                  HAVING YEAR(MAX(SaleDate))<2009)

在MySQL中

DELETE FROM Customer
WHERE CustID IN ( SELECT CustNo FROM Sale 
                  GROUP BY CustNo
                  HAVING EXTRACT(YEAR FROM MAX(SaleDate))<2009)