ORACLE SQL在某个日期订购的客户数

jckbn6z7  于 2023-01-20  发布在  Oracle
关注(0)|答案(2)|浏览(87)

我涉及到两个表,“customers”表和“orders”表。

***“customers”***表具有以下列:

Customerid, companyname, contactname, contactittle, addresses, city

***“订单”***表包含以下列:

orderid, customerid, employeeid, orderdate, shippeddate, shipname

我必须做的是97年订购产品的客户数量在哪里出来。
应该是这样的

Number of clients 20

我试过下面的代码,但我认为它是错误的,原因有以下两个
1-我认为像'%97%'这样的问题将来可能会导致错误
2-出于某种原因,它需要我的订单数量已经作出,而不是客户的数量

SELECT DISTINCT(COUNT (companyname))as Numero_CLIENTES
FROM customers JOIN orders ON customers.customerid=orders.customerid
WHERE orderdate like '%97%'
zvokhttg

zvokhttg1#

样本数据:

SQL> with
  2  customers (customerid) as
  3    (select 1 from dual union all
  4     select 2 from dual union all
  5     select 3 from dual
  6    ),
  7  orders (orderid, customerid, orderdate) as
  8    (select 100, 1, date '1997-12-02' from dual union all  --> customer 1 counts as "1"
  9     select 101, 1, date '2000-03-28' from dual union all
 10     select 102, 2, date '1997-05-29' from dual union all  --> customer 2 counts as "1" as well
 11     select 103, 2, date '1997-06-12' from dual            --> because both orders were made in 1997
 12    )

质询:

13  select count(distinct c.customerid) numero_clientes
 14  from customers c join orders o on o.customerid = c.customerid
 15  where extract(year from o.orderdate) = 1997;

NUMERO_CLIENTES
---------------
              2

SQL>
deyfvvtc

deyfvvtc2#

DISTINCT是关键字,不是函数。
您可以使用一个日期范围,并将DISTINCT放入聚合中,以便获得不同公司名称的计数:

SELECT COUNT(DISTINCT companyname) AS numero_clientes
FROM   customers c
       JOIN orders o
       ON c.customerid = o.customerid
WHERE  orderdate >= DATE '1997-01-01'
AND    orderdate <  DATE '1998-01-01'

您还可以使用以下任一项:

  • WHERE EXTRACT(YEAR FROM orderdate) = 1997
  • WHERE TO_CHAR(orderdate, 'YYYY') = '1997'

它会起作用的但是,在这些情况下,Oracle不会使用orderdate列上的任何索引,而需要分别在EXTRACT(YEAR FROM orderdate)TO_CHAR(orderdate, 'YYYY')上使用基于函数的索引。如果使用日期范围,则Oracle可以在orderdate列上使用索引。

相关问题