在SQL

时间:2018-11-19 12:45:52

标签: sql tsql qsqltablemodel

我是sql的新手,请尝试找出数据透视表的“查找”列。我设法用第一列作为主键进行了数据透视。然后,我想从其他查询(即联接表)中添加一列。

我同时具有数据透视表和第二个查询,但是无法将它们附加在一起。你能帮我吗

枢轴代码 >

 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     Variant
           ,SUM(Sales) AS TotalSales
           ,SUM(Discount) AS TotalDisc

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

因此,我想在数据透视表旁边添加“销售总额”和“光盘总数”列。 因此,对于每个变体,我可以看到WH1中的库存,WH2中的库存,WH3中的sotkc,总销售额和总折扣。

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以在下面使用公用表表达式尝试加入

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