1

以下のようなシナリオがあります。

テーブルが二つありTransactionProduct

Transactionテーブルには列があります

Id, Amount ProductId TransactionDate ,DepartmentId
1,  100       100       01/01/2013       1
2,  200       101       02/01/2013       2 and so on....

Productテーブルには列があります

Id,   Name, ProductType.
100,  AB ,    1
101   C ,     2

次を出力する単一のストアドプロシージャを作成したい:

Month Year Department Count(Transactions) Count(Transactions of ProductType1) 
Feb   2012    1              100                        50 
Mar   2012    1              100                        50 
Apr   2012    1              100                        50 
Feb   2012    2              100                        50 

私はここまで来ました:

select 
    YEAR(T.TransactionDate) AS [YEAR],
    MONTH(T.TransactionDate) AS [MONTH], 
    Count(T.Id)
from 
    Transaction T 
INNER JOIN 
    Product P ON P.Id = T.ProductId
group by 
    T.DepartmentId, YEAR(T.TransactionDate), MONTH(T.TransactionDate);

以下を出力します。

Month Year Department Count(Transactions)

私も含める方法を知りたい:

Count(Transactions of ProductType1)

私もこれを試しました:

select 
    YEAR(T.TransactionDate) AS [YEAR],
    MONTH(T.TransactionDate) AS [MONTH],    
    Count(T.Id)
    (Select Count(T.Id)
     from Transaction T 
     INNER JOIN Product P ON P.Id = T.ProductId
     where P.Id = 1)
from 
     Transaction T 
INNER JOIN 
     Product P ON P.Id = T.ProductId
group by 
     T.DepartmentId, YEAR(T.TransactionDate), MONTH(T.TransactionDate);

group by 句が原因で、productid = 1 の場合、Transactions カウントの結果が不正確になります。

私は別のクエリを書きたくありません..しかし、SQLステートメントを取得して1つのクエリで以下を返す効率的な方法があるかどうかを知りたいですか?

 Month Year Department Count(Transactions) Count(Transactions of ProductType1) 
4

2 に答える 2

3

あなたは本当に近かったので、別の を追加する必要がありますが、式COUNTを使用しCASEます:

SELECT  YEAR(T.TransactionDate) AS [YEAR],
        MONTH(T.TransactionDate) AS [MONTH], 
        COUNT(T.Id) AS Transactions,
        SUM(CASE WHEN P.ProductType = 1 THEN 1 ELSE 0 END) AS TransactionsType1
FROM [Transaction] T 
INNER JOIN Product P 
    ON P.Id = T.ProductId
GROUP BY T.DepartmentId, YEAR(T.TransactionDate), MONTH(T.TransactionDate);
于 2013-03-28T14:50:54.960 に答える
2

PIVOT関数を使用して結果を取得することもできます。

select month, year, 
  departmentid, totalTransactions, 
  [1] ProductType1,
  [2] ProductType2
from
(
  select month(t.transactiondate) month,
    year(t.transactiondate) year,
    t.departmentid,
    p.productType,
    count(*) over(partition by month(t.transactiondate), 
                                year(t.transactiondate),
                                t.departmentid) totalTransactions
  from [transaction] t
  inner join Product p
    on p.id = t.productid
) s
pivot
(
  count(productType)
  for productType in ([1], [2])
) piv;

デモで SQL Fiddle を参照してください

于 2013-03-28T14:57:15.853 に答える