我正在使用以下屏幕截图获取数据 select VendorShortName,BasePrice,convert(varchar, ModifiedDate,101) as date from prices where barcode='8712566383849'
select VendorShortName,BasePrice,convert(varchar, ModifiedDate,101) as date from prices where barcode='8712566383849'
谁能帮我?
您可以使用PIVOT轻松完成此操作。这是您将如何获得此示例的示例。Firt Image将向您展示简单的PIVOT查询以及如何实现。
第二张图片将为您显示动态查询生成-这可能会更有用,因为根据您的图片看来您需要生成动态列,因此请参考第二张图片。
根据我在以下代码段中创建的查询-看看它是否对您有帮助。
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX) DECLARE @ColumnName AS NVARCHAR(MAX) --Get distinct values of the PIVOT Column SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(vendorshortname) FROM (select distinct vendorshortname from Prices) AS Prices --Prepare the PIVOT query using the dynamic SET @DynamicPivotQuery = N'SELECT ModifiedDate, ' + @ColumnName + ' FROM (select VendorShortName,BasePrice,ModifiedDate from prices where barcode=''8712566383849'') As SourceTable PIVOT (avg(BasePrice) FOR VendorShortName IN (' + @ColumnName + ')) AS PVTTable' --Execute the Dynamic Pivot Query EXEC sp_executesql @DynamicPivotQuery