使用相同 table 数据 SQL 服务器的多个连接

Multiple joins with the same table data SQL Server

我有一个 table 数据“销售额”,其中包含每个商店按产品和商店的销售额。

id sales shop
1 100.0 01
1 30.0 02
2 2.0 01
3 100.0 01
3 30.0 02
4 100.0 03
4 10.0 02

我尝试以一种格式获取数据,该格式为我提供同一行中每家商店的商品 ID 和销售额,如下所示:

id sales1 shop1 sales2 shop2 sales3 shop3
1 100.0 01 30.0 02 0.0 03
2 2.0 01 0.0 02 0.0 03
3 100.0 01 30.0 02 0.0 03
4 0.0 01 10.0 02 100.0 03

我尝试将数据与一些 (select * from sales where shop='01') 作为 a 左连接,但它不起作用,因为 ON 子句仅与一个连接 table,在这种情况下,a.

这里是 SQL 查询:

select * 
from 
    (select * 
     from sales 
     where shop = '01') as a 
left join
    (select * 
     from sales 
     where shop = '02') as b on a.id = b.id 
left join
    (select * 
     from sales 
     where shop = '03') as c on a.id = c.id

按照这个逻辑,我丢失了数据的结果 4、10.0、02,试图更改 ON 子句,如 c.id = b.id 加入不同的数据并给我不同的结果。

我该如何解决这个问题?

不太确定为什么每个商店价值都有一列。当您有 Sales1、Sales2 等时,这似乎是多余的。但是通过使用条件聚合,您可以比所有这些查询更容易地解决这个问题。像这样的东西应该适合你。

select id
    , Sales1 = isnull(max(case when Shop = '01' then sales end), 0)
    , Shop1 = '01'
    , Sales2 = isnull(max(case when Shop = '02' then sales end), 0)
    , Shop2 = '02'
    , Sales3 = isnull(max(case when Shop = '03' then sales end), 0)
    , Shop3 = '03'
from sales
group by id