2013-01-31 124 views
0

這兩個SQL語句給了我下面顯示的結果。我需要爲MerchantIdBatchIdCurrency在SQL Server中連接兩個表

分組來連接他們,我需要一個包含所有這些列

MerchantId - BatchId - T1 - T2- NotSold - Sold- Currency 

查詢新表:

select 
    MerchantId as MerchantId, 
    BatchId as BatchId, 
    COUNT(BatchId)as T1, SUM(Amount) as NotSold, 
    Currency as Currency 
from 
    [Order] 
where 
    OrderStatus = 4 and MerchantId = 1 
group by 
    BatchId, Currency,MerchantId 

select 
    MerchantId as MerchantId, 
    BatchId as BatchId, 
    COUNT(BatchId) as T2, 
    SUM(Amount) as Sold, 
    Currency 
from 
    [Order] 
where 
    OrderStatus = 1 and MerchantId = 1 
group by 
    BatchId, Currency,MerchantId 
+1

你的最終輸出是什麼樣的? – codingbiz

回答

2

您將要使用的聚合函數與CASE表達:

select MerchantId as MerchantId, 
    BatchId as BatchId, 
    count(case when OrderStatus = 4 then BatchId end) T1, 
    count(case when OrderStatus = 1 then BatchId end) T2, 
    sum(case when OrderStatus = 4 then Amount else 0 end) NotSold, 
    sum(case when OrderStatus = 1 then Amount else 0 end) Sold, 
    Currency as Currency 
from [Order] 
where MerchantId = 1 
group by BatchId, Currency, MerchantId 

SQL Fiddle with Demo

使用您的樣本數據的結果是:

| MERCHANTID | BATCHID | T1 | T2 | NOTSOLD | SOLD | CURRENCY | 
-------------------------------------------------------------- 
|   1 |  1 | 1 | 1 |  11 | 11 |  TR | 
|   1 |  2 | 0 | 1 |  0 | 11 |  TR | 
|   1 |  3 | 1 | 1 |  11 | 11 |  TR | 
|   1 |  4 | 2 | 1 |  22 | 11 |  TR | 
|   1 |  1 | 2 | 2 |  22 | 22 |  USD | 
|   1 |  2 | 2 | 1 |  22 | 11 |  USD | 
|   1 |  4 | 0 | 1 |  0 | 11 |  USD | 
+0

嘿@bluefeet - 問題,OrderStatus會如何等於4,因爲你的Where OrderStatus = 1?不過,認爲它應該沒有Where子句。一如既往的好回答! – sgeddes

+0

我不知道我可以使用,如果在aggerate函數的情況下。非常感謝你。 –

+0

@Ryu是的,這就是你如何在sql server的一個數據透視函數之前使用'PIVOT'數據。 :) 樂於幫助!! – Taryn

0

假設貨幣是在同這兩個表,並且你想結合你的上述查詢,像這樣(未經測試)應該工作:

select O.MerchantId , 
    O.BatchId , 
    COUNT(O.BatchId)as T1, 
    SUM(O.Amount) as NotSold , 
    COUNT(O2.BatchId) as T2, 
    SUM(O2.Amount) as Sold , 
    O.Currency 
from [Order] O 
    LEFT JOIN [Order] O2 ON O.MerchantId = O2.MerchantId 
      AND O.BatchId = O2.BatchId 
      AND O.Currency = O2.Currency 
      AND O2.OrderStatus = 1 and O2.MerchantId = 1 
where O.OrderStatus = 4 and O.MerchantId = 1 
group by O.BatchId, O.Currency, O.MerchantId 
0
SELECT * 
FROM t1, t2 
LEFT JOIN t1.MerchantId ON t2.MerchantId = t1.MerchantId 

,然後將其擴展爲在batchId上執行,並僅選擇所需的列作爲結果(rath呃比*)