1

我有一个表交易和一个表产品,如下所示。每个交易都有多个产品。

  ProductId Name
      1      ABC
      2      DEF
      3      GHI

每笔交易可以销售多个产品。

TransactionId ProductSoldInDept1 ProductSoldinDept2 ProductSoldinDept3
        1         1                       null         null
        2         1                        2           null
        3         3                        1           null
        4         2                        3             1  

我打算生成一份报告,我想得到这样的结果:

这显示了按 Id 分组的每个部门销售的产品数量

预期结果 :

ProductID Department1ProdCount Department2ProdCount Department3ProdCount 
  1           2                           1             1                    
  2           1                           1             0
  3           1                           1             0 

我可以到这里,这是一个查询,用于获取一个特定产品的计数,它是 productid:1 我想知道如何在这里使用一个组:

select Count(CASE WHEN ProductSoldInDept1 = 1 THEN 1 END) ,
    Count(CASE WHEN ProductSoldInDept2 = 1 THEN 1 END) ,
      Count(CASE WHEN ProductSoldInDept3 = 1 THEN 1 END)
from   Table1 
4

3 回答 3

4
SELECT
  p.ProductID,
  Dept1ProdCount = COUNT(CASE WHEN t.ProductSoldInDept1 = p.ProductID THEN 1 END),
  Dept2ProdCount = COUNT(CASE WHEN t.ProductSoldInDept2 = p.ProductID THEN 1 END),
  Dept3ProdCount = COUNT(CASE WHEN t.ProductSoldInDept3 = p.ProductID THEN 1 END)
FROM dbo.Product AS p
LEFT OUTER JOIN dbo.[Transaction] AS t
ON p.ProductID IN  
  (t.ProductSoldInDept1, t.ProductSoldinDept2, t.ProductSoldinDept3)
GROUP BY p.ProductID;

结果

| 产品ID | DEPT1PRODCOUNT | DEPT2PRODCOUNT | DEPT3PRODCOUNT |
-------------------------------------------------- --------------
| 1 | 2 | 1 | 1 |
| 2 | 1 | 1 | 0 |
| 3 | 1 | 1 | 0 |

查看演示

于 2013-04-19T18:50:36.970 回答
0

尝试这个

select ProductID, 
v.Department1ProdCount, v.Department2ProdCount, v.Department3ProdCount
from product a
cross apply 
(
 select Count(CASE WHEN ProductSoldInDept1 = a.ProductID THEN 1 END) Department1ProdCount,
 Count(CASE WHEN ProductSoldInDept2 = a.ProductID THEN 1 END) Department2ProdCount,
 Count(CASE WHEN ProductSoldInDept3 = a.ProductID THEN 1 END) Department3ProdCount
 from  Table1
) v
于 2013-04-19T18:48:55.270 回答
0

这个:

  TransactionId ProductSoldInDept1 ProductSoldinDept2 ProductSoldinDept3
    1         1                       null         null
    2         1                        2           null
    3         3                        1           null
    4         2                        3             1  

可能更好的结构是这样的:

transid   prodsold    deptid
1         1           1
2         1           1
2         2           2
3         3           1
3         1           2
4         2           1
4         3           2
4         1           3

我认为这将使您的查询更容易编写。

于 2013-04-19T18:53:54.743 回答