简体   繁体   English

SQL-创建数据透视表

[英]SQL - Create pivot table

I'm trying to create a pivot table from data in a number of tables, but I can't get it to work. 我正在尝试根据多个表中的数据创建数据透视表,但无法使其正常工作。 This is the database structure: 这是数据库结构:

在此处输入图片说明

So the tables would look like: 因此表如下所示:

在此处输入图片说明

What I would like to create is a pivot table combining all sales data from customers per product like this: 我要创建的数据透视表将每个产品来自客户的所有销售数据组合在一起,如下所示:

在此处输入图片说明

(This data is to be fed into a different system which requires this as input, so I can't change the format) (此数据将被输入到需要此数据作为输入的其他系统中,因此我无法更改格式)

However, I have no idea how to accomplish this. 但是,我不知道该如何完成。 I tried this: 我尝试了这个:

select distinct c.name, 
       p.name,
       sum(p.price)        
FROM customer c
  left join sale s on c.customerId = s.customerId
  left outer join product p ON s.productId = p.productId
group by s.productId, s.customerId

I know it's not much, but I'm having a hard time wrapping my head around it. 我知道不多,但是我很难把头缠在它上面。 Can anyone help me get on track? 谁能帮助我步入正轨?

Cheers, CJ 干杯,CJ

Its very easy, you can pivot it by custom case when statements: 它非常简单,您可以在以下情况下通过自定义案例来进行旋转:

select c.name, 
sum(CASE WHEN p.name = 'Product X' THEN p.price ELSE 0 END) AS "Product X",
sum(CASE WHEN p.name = 'Product Y' THEN p.price ELSE 0 END) AS "Product Y",
sum(CASE WHEN p.name = 'Product Z' THEN p.price ELSE 0 END) AS "Product Z"
    FROM customer c
      left join sale s on c.customerId = s.customerId
      left outer join product p ON s.productId = p.productId
    group by c.customerId, c.name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM