0

これら 2 つの SQL ステートメントにより、以下に示す結果が得られます。をグループ化してそれらを連結する必要がありMerchantIdBatchIdCurrency

これらすべての列を含む新しいテーブルが必要です

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 に答える