2013-01-31 122 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呃比*)