如何通过连接两个表来获取条件列?

时间:2014-08-12 13:41:39

标签: sql sql-server sql-server-2008

我有两张桌子。一张是产品表,另一张是发货台。

Product
-------
ProductID   ProductName
1           Test1
2           Test2
Shipping
--------
ProductID   ShippingOption  Cost
1           Ground          0
1           SecondDay       100
1           OverNight       200
2           Ground          0
2           SecondDay       110

现在我想创建一个像

这样的报告
 Productid  IsGround    GroundCost  IsSecondDay SecondDayCost   IsOvernight OvernightCost
 1            1           0            1          100            1           200
 2            1           0            1          110            0           NULL

我尝试过使用join但实际上无法理解如何继续。请帮助我新编写SQL查询。

2 个答案:

答案 0 :(得分:1)

试试这个

select ProductID,
sum(case when ShippingOption='Ground' then 1 else 0 end) ISGrouped,
sum(case when ShippingOption='Ground' then  Cost else 0 end) GroupCost,
sum(case when ShippingOption='SecondDay' then 1 else 0 end) ISSecondDay,
sum(case when ShippingOption='SecondDay' then  Cost else 0 end) SecondDayCost,
sum(case when ShippingOption='OverNight' then 1 else 0 end)ISOverNight,
sum(case when ShippingOption='OverNight' then  Cost else 0 end)
OverNightCost from Shipping group by ProductID

Sql Fiddle

答案 1 :(得分:0)

如果您打算向用户提供看起来像这样的报告,那么最好的选择是"矩阵报告" (至少它在SSRS中被称为)。它将以比任何类型的SQL查询更加可扩展的方式为您完成所有的旋转。

相关问题