2016-01-28 42 views
0

我一直在建議使用樞軸SQL Server和它正在與該代碼加入在SQL Server轉動表

select 
    cs.DateAdded as 'Date', cs.Invoice, cu.StoreName as 'Store', 
    cu.AccountName as 'Customer', cu.StoreAddress as 'Address', 
    SUM(Case cs.ProductId WHEN '2' THEN Quantity ELSE 0 END) as '700', 
    SUM(case cs.ProductId WHEN '2' THEN Amount ELSE 0 END) as '700 Amount', 
    SUM(case cs.ProductId WHEN '1' THEN Quantity ELSE 0 END) as '350', 
    SUM(case cs.ProductId WHEN '1' THEN Amount ELSE 0 END) as '350 Amount', 
    SUM(case cs.ProductId WHEN '3' THEN Quantity ELSE 0 END) as '1L', 
    SUM(case cs.ProductId WHEN '3' THEN Amount ELSE 0 END) as '1L Amount' 
from 
    ConsignmentSale cs 
left join 
    Customer cu on cs.CustomerId=cu.CustomerId 
group by 
    cs.Invoice, cs.CustomerId, cu.AccountName, cu.StoreAddress, 
    cs.DateAdded, cu.StoreName 

這有點靜態的,因爲如果我們得到另一種產品,那麼我將不得不添加相應的產品ID。現在好了。但我真正關心的是;此聲明僅適用於ConsignmentSale表。我有一個CashSale表具有相同的結構或場爲ConsignmentSale表所以可以只使用相同的代碼如上述,改變from ConsignmentSalefrom CashSale

然而,問題是,我怎麼能連接兩個表,所以我會得到所有的結果,只是有一列,用於說明它「寄存」或「現金」?我知道我會以某種方式需要連接表,但我不知道在哪裏加入它們。

回答

1

這聽起來像你想的工會表到一個虛擬表,該結果適用於您的支點。

SELECT 
    * 
FROM 
(
    select 
     TableType=1,--INDICATES CONSIGNMENT 
     cs.DateAdded as 'Date', cs.Invoice, cu.StoreName as 'Store', 
     SUM(Case cs.ProductId WHEN '2' THEN Quantity ELSE 0 END) as '700', 
     SUM(case cs.ProductId WHEN '2' THEN Amount ELSE 0 END) as '700 Amount', 
     SUM(case cs.ProductId WHEN '1' THEN Quantity ELSE 0 END) as '350', 
     SUM(case cs.ProductId WHEN '1' THEN Amount ELSE 0 END) as '350 Amount', 
     SUM(case cs.ProductId WHEN '3' THEN Quantity ELSE 0 END) as '1L', 
     SUM(case cs.ProductId WHEN '3' THEN Amount ELSE 0 END) as '1L Amount' 
from 
     ConsignmentSale cs 
     left join Customer cu on cs.CustomerId=cu.CustomerId 

UNION ALL 

    select 
     TableType=2,--INDICATES CASH 
     cs.DateAdded as 'Date', cs.Invoice, cu.StoreName as 'Store', 
     SUM(Case cs.ProductId WHEN '2' THEN Quantity ELSE 0 END) as '700', 
     SUM(case cs.ProductId WHEN '2' THEN Amount ELSE 0 END) as '700 Amount', 
     SUM(case cs.ProductId WHEN '1' THEN Quantity ELSE 0 END) as '350', 
     SUM(case cs.ProductId WHEN '1' THEN Amount ELSE 0 END) as '350 Amount', 
     SUM(case cs.ProductId WHEN '3' THEN Quantity ELSE 0 END) as '1L', 
     SUM(case cs.ProductId WHEN '3' THEN Amount ELSE 0 END) as '1L Amount' 
from 
     Cash cs 
     left join Customer cu on cs.CustomerId=cu.CustomerId 
)AS Detail 
group by Detail.Invoice, Detail.CustomerId, Detail.AccountName, Detail.StoreAddress, Detail.DateAdded, Detail.StoreName 
+0

呀!而已!謝謝! – Ibanez1408