以下のようなシナリオがあります。
テーブルが二つありTransaction
、Product
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)