将SQL查询结果组合到另一个查询中 - 加入

时间:2016-09-29 13:41:48

标签: sql sql-server sql-server-2008

我想从query1获取查询结果,特别是RMA编号(oe_line.order_no),然后在query2 where语句中使用该结果,然后将两个查询连接在一起。这是我的代码;

select *
from
(
SELECT
    customer.customer_name 'Customer Name',
    invoice_line.invoice_no 'Invoice Number',
    invoice_line.order_no 'Invoice Order Number',
    invoice_line.qty_requested 'Invioice Qty Ordered', 
    invoice_line.extended_price 'Invoice Extended Price',
    invoice_line.item_desc 'Invoice Item Desc',
    oe_hdr.taker 'Order Taker',
    oe_hdr.location_id 'Sales Location ID',
    oe_hdr.source_location_id 'Source Location ID',
    oe_line.order_no 'RMA Number',
    oe_line.qty_ordered 'RMA Quantity',
    oe_line.extended_price 'RMA Extended Price',
    oe_line.extended_desc 'Extended Desc'

FROM oe_line

INNER JOIN oe_line_rma ON (oe_line_rma.oe_line_uid = oe_line.oe_line_uid)
INNER JOIN invoice_line ON (invoice_line.invoice_line_uid = oe_line_rma.invoice_line_uid)
INNER JOIN oe_hdr ON (oe_hdr.order_no = oe_line.order_no)
INNER JOIN customer ON (customer.customer_id = oe_hdr.customer_id) 

where CONVERT( varchar(10), oe_line_rma.date_created,101) = '09/22/2016' /* CONVERT(VARCHAR(10),GETDATE(),101)*/
) rsQuery1
FULL OUTER JOIN
(
SELECT
    oe_hdr.order_no, oe_hdr.taker 'RMA Order Taker',
    oe_hdr.location_id 'RMA Credit Location',
    oe_hdr.source_location_id 'RMA Source Location'
from oe_hdr
where oe_hdr.order_no = rsQuery1.[RMA Number] /* result from RMA Number on rsQuery1 */
) rsQuery2 on rsQuery1.[RMA Number] = rsQuery2.order_no 

我想要的输出看起来与此相似;

| Customer Name | Invoice Number | Invoice Order Number | Invoice Qty Ordered | Invoice Extended Price | Invoice Item Desc | Order Taker | Sales Location ID | Source Location ID | RMA Number | RMA Quantity | RMA Extended Price | Extended Desc  | Order_no | RMA Order Taker | RMA Credit Location | RMA Source Location |
|---------------|----------------|----------------------|---------------------|------------------------|-------------------|-------------|-------------------|--------------------|------------|--------------|--------------------|----|-------------|----------|-----------------|---------------------|---------------------|
| ABC Company   |        4236 |                55995 |                  10 |                   2000 | Metallic Rings    | asmith      |                10 |                 10 |       6785 |          -10 |              -2000 | Metallic Rings |     6785 | asmith          |                  10 |                  10 |

我现在可以通过手动匹配查询的where语句中的值来实现此输出。产生输出;

rsQuery1其中invoice_line.invoice_no ='4236' rsQuery2其中oe_hdr.order_no ='6785'

我的最终目标是根据rma创建日期=今天返回rsQuery1中的数据,并获取该结果以从RMA编号生成rsQuery2的结果。我最终会将这些数据放入表中以生成报告。

1 个答案:

答案 0 :(得分:1)

我理解的是这样的。现在你想要的连接不清楚。

  SELECT *
  FROM tableA
  WHERE tableA.RMA = (SELECT RMA
                      FROM tableB
                      WHERE <somecondition>)