我有一个查询,我试图将行值转换为列名,目前正在使用SUM(Case…) As ‘ColumnName’语句如下:9 ^5 U5 R8 ]" R" l. |6 s
SELECTSKU1,SUM(Case When Sku2=157 Then Quantity Else 0 End) As '157',SUM(Case When Sku2=158 Then Quantity Else 0 End) As '158',SUM(Case When Sku2=167 Then Quantity Else 0 End) As '167'FROMOrderDetailDeliveryReviewGroup ByOrderShipToID,DeliveryDate,SKU1 以上查询效果很好,给了我确切的需求。但是,我会SUM(Case…根据以下查询结果手动写句:* b" N& o/ E5 ?, a. x
Select Distinct Sku2 From OrderDetailDeliveryReview 存储过程中有没有办法使用?T-SQL,从而可以SUM(Case...从Select Distinct Sku2 From OrderDetailDeliveryReview查询中动态生成语句,然后执行生成语句SQL代码? " |% ~+ h+ j+ n8 G * ?; Q4 z- ~- q8 D- a 解决方案: ! J, r8 X8 B6 U8 }
在您的特定情况下(使用)ANSI而不是数据透视表SQL Server 2005的PIVOT功能):- Q* ]) S3 h x* k# A
DECLARE @template AS varchar(max)SET @template = 'SELECT SKU1{COLUMN_LIST}FROMOrderDetailDeliveryReviewGroup ByOrderShipToID,DeliveryDate,SKU1'DECLARE @column_list AS varchar(max)SELECT @column_list = COALESCE(@column_list,SUM(Case When Sku2=' CONVERT(varchar,Sku二、 Then Quantity Else 0 End) As CONVERT(varchar,Sku2) '],' FROM OrderDetailDeliveryReviewGROUP BY Sku2ORDER BY Sku2Set @column_list = Left(@column_list,Len(@column_list)-1)SET @template = REPLACE(@template,'{COLUMN_LIST}',@column_list)EXEC (@template)