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

我不想编写单独的查询..但我想知道是否有一种有效的方法可以让 SQL 语句在一个查询中返回以下内容?

 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 回答