我有一个类似于下面的场景:
有两张桌子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
我不想编写单独的查询..但我想知道是否有一种有效的方法可以让 SQL 语句在一个查询中返回以下内容?
Month Year Department Count(Transactions) Count(Transactions of ProductType1)