查询计算已连接表中的所有项目

时间:2016-02-14 09:59:13

标签: sql

我有三张桌子:

帐户:

AccountId | AccountEmail

PurchasedProducts:

ProductName | AccountId | ProductTypeId

ProductTypes:

ProductTypeId | ProductTypeName

我想创建一个查询,计算每个帐户每种产品类型的已购买产品数量。看起来应该是这样的:

AccountEmail  | ProductTypeName A | ProductTypeName B | ProductTypeName C
-------------------------------------------------------------------------
peter@test.nl | 0                 | 12                | 1

我无法弄清楚如何进行此查询...任何人都可以帮忙吗?提前谢谢!

2 个答案:

答案 0 :(得分:1)

这样的东西会起作用

SELECT accountemail, 
       Sum(CASE 
             WHEN producttypename = 'ProductTypeName A' THEN 1 
             ELSE 0 
           END) AS 'ProductTypeName A', 
       Sum(CASE 
             WHEN producttypename = 'ProductTypeName B' THEN 1 
             ELSE 0 
           END) AS 'ProductTypeName B', 
       Sum(CASE 
             WHEN producttypename = 'ProductTypeName C' THEN 1 
             ELSE 0 
           END) AS 'ProductTypeName C' 
FROM   purchasedproducts p 
       INNER JOIN producttypes ot 
               ON p.producttypeid = pt.producttypeid 
       INNER JOIN account a 
               ON a.accountid = p.accountid 
WHERE  producttypename IN ( 'ProductTypeName A', 'ProductTypeName B', 
                            'ProductTypeName C' ) 
GROUP  BY accountemail 

答案 1 :(得分:0)

以下(基于@ VR46的回答)将给出正确的值,但不是OP提供的确切表格格式。我认为,这应该足以满足大多数用途,如果需要每列producttype格式,可以使用Excel或其他查询创建数据透视表

SELECT accountemail, producttypename, COUNT(*)
FROM   purchasedproducts p 
       INNER JOIN producttypes ot 
               ON p.producttypeid = pt.producttypeid 
       INNER JOIN account a 
               ON a.accountid = p.accountid 
GROUP  BY accountemail, producttypename