Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用于汇总三个表的SQL查询_Sql_Pivot - Fatal编程技术网

用于汇总三个表的SQL查询

用于汇总三个表的SQL查询,sql,pivot,Sql,Pivot,假设我有一个具有以下结构的数据库: Customers ID Name 1 Bob 2 Jim 3 Sally Products ID Description 10 Pencil 11 Ruler 12 Eraser Purchases ID Customer_ID Product_ID 1 1 10 2 1 11 3 2 10 4 3 12 是否有可能(无需为每个客户、每个产品执行查询)编写查询以获得如下格式: Cu

假设我有一个具有以下结构的数据库:

Customers  
ID Name  
1  Bob  
2  Jim  
3  Sally  

Products  
ID Description  
10 Pencil  
11 Ruler  
12 Eraser  

Purchases  
ID Customer_ID Product_ID  
1 1 10  
2 1 11    
3 2 10  
4 3 12 
是否有可能(无需为每个客户、每个产品执行查询)编写查询以获得如下格式:

Customer Pencil Ruler Eraser  
1 1 1 0  
2 1 0 0  
3 0 0 1  
这就是我得到的,但我想避免这种结构,因为它会变得冗长,产品的数量也会发生变化。此外,当客户确实购买了产品10时,我会得到重复的行:

  SELECT DISTINCT CUSTOMER.CUSTOMER_ID, (case when a.CUSTOMER_ID = 
    CUSTOMER.CUSTOMER_ID THEN 1 ELSE 0 END) as product10
    from 
    (SELECT PURCHASES.CUSTOMER_ID from PURCHASES
    WHERE PURCHASES.PRODUCT_ID = 10) a, CUSTOMER

CUSTOMER_ID product10  
1 1  
1 0  
2 1  
2 0  
3 0  
谢谢

您可以尝试以下方法:

SELECT DISTINCT t1.ID, t3.ID 
FROM Customers t1 
INNER JOIN Purchases t2 
   ON t1.ID = t2.Customer_ID 
INNER JOIN Products t3 
   ON t2.Product_ID = t3.ID;
它不会返回客户在一行中拥有的所有内容,但会返回客户与产品之间存在关系且不存在重复项的所有行

您可以执行条件聚合:

select c.id, sum(case when p.Description = 'Pencil' then 1 else 0 end) as Pencil,
             sum(case when p.Description = 'Ruler' then 1 else 0 end) as Ruler,
             sum(case when p.Description = 'Eraser' then 1 else 0 end) as Eraser
from Purchases prc inner join 
     Customers c
     on c.id = prc.Customer_ID inner join
     Products p 
     on p.id = prc.Product_ID  
group by c.id;