SQL表连接和子查询

问题描述:

我需要将3个表连接在一起,并从中获取日期,价格和客户ID。这里的介绍:SQL表连接和子查询

First you need to figure out the customer id’s of anyone who purchased a product with the division of ‘Bike Accessories’ from Jan 1, 2012 till now. To get this you will need to join orders to orderlines to products.

Then in your parent query, you will join orders to orderlines and filter on customer id’s that are in your subquery results. To calculate lifetime order revenue you’ll need to do an aggregate function on the result of price * quantity.

所以我有一个客户ID,与订单号,价格和数量,与客户ID订单表,订单号和订单日期的orderlines表中的客户表,和产品与分区表(需要获得'自行车配件'检索)。我已经写了这个,并且根据我四处移动的情况,我从“无效标识符”到“缺少的表达式”中收到了错误。

select bc_orders.order_number, bc_orderlines.price, bc_orderlines.quantity, bc_orderlines.quantity*bc_orderlines.price AS "Total Revenue" 
    from (select bc_orders.*, bc_orderlines.*, bc_products.* 
    from bc_customers 
    join bc_orders 
    on bc_orders.order_number = bc_orderlines.order_number 
    join bc_products 
    on bc_products.sku = bc_orderlines.sku 

where bc_orders.order_date >= '01-JAN-2012') 

inner join bc_orderlines 
    on bc_orders.order_number = bc_orderlines.order_number 

我回来:

Error at Command Line:5 Column:31
Error report:
SQL Error: ORA-00904: "BC_ORDERLINES"."ORDER_NUMBER": invalid identifier

帮助!

from子句的计算方式与您阅读的相同。这意味着在可以在on子句中提及表别名之前,需要将其定义为表。在定义之前,您正在使用orderlines。因此错误。

这很容易固定:

从(选择bc_orders *,bc_orderlines *,bc_products * 从bc_customers加入上bc_orders.customer_number = bc_customers.customer_number bc_orders 上bc_orders.order_number加入 bc_orderlines 。 = bc_orderlines.order_number加入 bc_products 上bc_products.sku = bc_orderlines.sku 其中bc_orders.order_date> = '01 -JAN-2012' )BC

一些注意事项:

  • 我还没有解决查询中的所有问题,只是您询问的问题。
  • 你不需要子查询。
  • 使用表别名,您的查询将更具可读性。我鼓励你使用它们。
  • 所写的子查询将有不明确的列。