0

这两个 SQL 语句给了我如下所示的结果。我需要通过分组来连接它们MerchantIdBatchId并且Currency

我需要一个包含所有这些列的新表

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
4

3 回答 3

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

使用您的样本数据,结果是:

| 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 |
于 2013-01-31T23:39:33.557 回答
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
于 2013-01-31T23:38:37.630 回答
0
SELECT *
FROM t1, t2
LEFT JOIN t1.MerchantId ON t2.MerchantId = t1.MerchantId

然后将其放大以在batchId上执行,并仅选择您想要的列作为结果(而不是*)

于 2013-01-31T23:39:54.563 回答