假设我有一个具有以下结构的数据库:
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
谢谢!
答案 0 :(得分:1)
您可以执行条件聚合:
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;
答案 1 :(得分: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;
它不会返回客户在一行中拥有的所有内容,但它会返回客户与产品之间的关系不存在重复的所有行。