我有一个类似下面的场景:
有两个表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语句在一个查询中返回以下内容?
Month Year Department Count(Transactions) Count(Transactions of ProductType1)
答案 0 :(得分: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);
答案 1 :(得分: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;