我的sql server中有一个名为VendorItemPricing的表。
select * from VendorItemPricing where ItemID = 122
此查询将为我提供以下结果。
ItemID VendorName VendorPrice UpdatedDate ObsoleteItem
122 HP 215.13 2015-05-15 11:55:49.983 0
122 IBM 264.41 2015-05-15 11:56:04.990 0
122 Microsoft 257.65 2015-05-15 11:56:23.963 0
我希望HP,Apple,...列在行的列上,所以我使用了数据透视表
Select ItemID,
[HP] As HPUpdatedDate,
[Apple] As AppleUpdatedDate,
[Microsoft] As MicrosoftUpdatedDate,
[IBM] As IBMUpdatedDate from (
select Itemid,Vendorname,UpdatedDate from VendorItemPricing where ItemID = 122)A
PIVOT(
MAX(UpdatedDate) FOR Vendorname IN ([HP],[Apple],Microsoft,IBM)
)P
以上查询结果如:
ItemID HPUpdatedDate AppleUpdatedDate MicrosoftUpdatedDate IBMUpdatedDate
122 2015-05-15 11:55:49.983 NULL 2015-05-15 11:56:23.963 2015-05-15 11:56:04.990
和
Select ItemID,
[HP] As HPPrice ,
[Apple] As ApplePrice,
[Microsoft] As MicrosoftPrice,
[IBM] As IBMPrice from (
select Itemid,Vendorname,VendorPrice from VendorItemPricing where ItemID = 122)A
PIVOT(
MAX(VendorPrice) FOR Vendorname IN ([HP],[Apple],Microsoft,IBM)
)P
以上查询结果如:
ItemID HPPrice ApplePrice MicrosoftPrice IBMPrice
122 215.13 NULL 257.65 264.41
和
Select ItemID,
[HP] As HPObsoleteItem,
[Apple] As AppleObsoleteItem,
[Microsoft] As MicrosoftObsoleteItem,
[IBM] As IBMObsoleteItem from (
select Itemid,Vendorname,CAST(ObsoleteItem AS TINYINT) AS INTColumn from VendorItemPricing where ItemID = 122)A
PIVOT(
MAX(INTColumn) FOR Vendorname IN ([HP],[Apple],Microsoft,IBM)
)P
以上查询结果如:
ItemID HPObsoleteItem AppleObsoleteItem MicrosoftObsoleteItem IBMObsoleteItem
122 0 NULL 0 0
是否有可能获得如下结果?抱歉这个冗长的问题。任何帮助都感激不尽。
ItemID HPUpdatedDate AppleUpdatedDate MicrosoftUpdatedDate IBMUpdatedDate HPPrice ApplePrice MicrosoftPrice IBMPrice HPObsoleteItem AppleObsoleteItem MicrosoftObsoleteItem IBMObsoleteItem
122 2015-05-15 11:55:49.983 NULL 2015-05-15 11:56:23.963 2015-05-15 11:56:04.990 215.13 NULL 257.65 264.41 0 NULL 0 0
答案 0 :(得分:0)
您可以使用子查询或CTE,然后根据ItemID连接所有三个查询以获取所有必要字段:
{{1}}