如何从以下两个查询中选出一个

时间:2019-03-13 13:05:41

标签: join sql-server-2012

我有两个查询:

第一个查询是:

SELECT sale.saleid, 
   sale.totalpaid, 
   item.itemname         AS item, 
   stock.saleprice       AS Price, 
   invoice.qty, 
   sale.discount, 
   invoice.saleprice     AS [invoice saleprice], 
   cetegory.catname      AS [Cateogory], 
   cetegory.subcat       AS [Sub Catgry], 
   vehicle.vehicle_name  AS [Vehicle], 
   vehicle.vehicle_model AS [Model], 
   item.model_number     AS [Part No.], 
   sale.date, 
   stock.size, 
   sale.customerid 
FROM   invoice 
       JOIN item 
         ON invoice.itemid = item.itemid 
       JOIN sale 
         ON invoice.saleid = sale.saleid 
       JOIN stock 
         ON item.itemid = stock.itemid 
       JOIN cetegory 
         ON item.catid = cetegory.catid 
       JOIN vehicle 
         ON item.vehicleid = vehicle.vehicleid 
WHERE  sale.saleid = 5 

第二个查询是:

SELECT customer.customername, 
       customer.customercontact, 
       customer.customeraddress, 
       account.account_type 
FROM   account 
       JOIN customer 
         ON customer.customerid = account.customerid 

现在,我想按客户ID组合这两个查询,因为我在销售表中有“客户ID”

1 个答案:

答案 0 :(得分:0)

您可以使用CTE,然后同时加入两者:

 WITH CUST
 AS
  (SELECT customer.customername, 
   customer.customercontact, 
   customer.customeraddress, 
   account.account_type ,
   customer.customerid
 FROM   account 
   JOIN customer 
     ON customer.customerid = account.customerid 
 ),

 SALES
 AS
 (
 SELECT sale.saleid, 
 sale.totalpaid, 
 item.itemname         AS item, 
 stock.saleprice       AS Price, 
 invoice.qty, 
 sale.discount, 
 invoice.saleprice     AS [invoice saleprice], 
 cetegory.catname      AS [Cateogory], 
 cetegory.subcat       AS [Sub Catgry], 
 vehicle.vehicle_name  AS [Vehicle], 
 vehicle.vehicle_model AS [Model], 
 item.model_number     AS [Part No.], 
 sale.date, 
 stock.size, 
 sale.customerid 
 FROM   invoice 
   JOIN item 
     ON invoice.itemid = item.itemid 
   JOIN sale 
     ON invoice.saleid = sale.saleid 
   JOIN stock 
     ON item.itemid = stock.itemid 
   JOIN cetegory 
     ON item.catid = cetegory.catid 
   JOIN vehicle 
     ON item.vehicleid = vehicle.vehicleid 
 WHERE  sale.saleid = 5 
 )

SELECT * FROM CUST
LEFT JOIN SALES
ON CUST.customerid = SALES.customerid