将不同 table 的列添加到 SQL 上的枢轴 table

Adding a column from a diffent table to a pivot table on SQL

我是 sql 的新手,我试图找出一个 "lookup" 列到一个枢轴 table。我设法用第一列作为主键创建了一个数据透视表。然后我想添加来自不同查询的列,即来自 joined tables.

我的数据透视表 table 和第二个查询都在工作,但无法将它们附加在一起。你能帮我吗

枢轴代码 >

 Select         Variant
                ,WH1
                ,WH2
                ,WH3 
FROM(
Select  WH
,Variant
,stock pieces 
FROM StockData
Where Date = cast(Getdate()-3 AS Date)

) Stock

Pivot( SUM(AtdPieces) FOR Warehouse  IN ([6492],[7318],[7348],[7347]) ) as Pvt
Order by Poznan desc;

第二个代码 table

Select     Variant
           ,SUM(Sales) AS TotalSales
           ,SUM(Discount) AS TotalDisc

From SalesDatabase as SDB
Join DiscountDatabase as DDB 
On SDB.Variant=DDB. Variant)

所以我想在我的数据透视 table 旁边添加 "total Sales" 和 "Total Disc" 列。 因此,对于每个变体,我可以看到 WH1 中的库存、WH2 中的库存、WH3 中的 sotk​​c、总销售额和总折扣。

非常感谢您的帮助!

您可以在下面尝试使用常见的 table 表达式并加入

with cte as
(
 Select         Variant
                ,WH1
                ,WH2
                ,WH3 
FROM(
Select  WH
,Variant
,stock pieces 
FROM StockData
Where Date = cast(Getdate()-3 AS Date)

) Stock

Pivot( SUM(AtdPieces) FOR Warehouse  IN ([6492],[7318],[7348],[7347]) ) as Pvt
Order by Poznan desc;
)

select cte.variant,WH1, WH2, WH3, SUM(Sales) AS TotalSales
           ,SUM(Discount) AS TotalDisc from cte join 
SalesDatabase as SDB on cte.variant=SDB.variant
Join DiscountDatabase as DDB On SDB.Variant=DDB.Variant
group by cte.variant,WH1, WH2, WH3