小编典典

动态SQL生成列名?

sql

我有一个查询,我正在尝试将行值转换为列名,当前正在使用SUM(Case…) As ‘ColumnName’语句,如下所示:

SELECT
SKU1,
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'
FROM
OrderDetailDeliveryReview
Group By
OrderShipToID,
DeliveryDate,
SKU1 

上面的查询效果很好,并且给了我确切的需求。但是,我将SUM(Case…根据以下查询的结果手动写出语句:

Select Distinct Sku2 From OrderDetailDeliveryReview 

有没有办法在存储过程中使用T-SQL,从而可以SUM(Case...Select Distinct Sku2 From OrderDetailDeliveryReview查询中动态生成语句,然后执行生成的SQL代码?


阅读 180

收藏
2021-05-23

共1个答案

小编典典

在您的特定情况下(使用ANSI数据透视表而不是SQL Server 2005的PIVOT功能):

DECLARE @template AS varchar(max)
SET @template = 'SELECT 
SKU1
{COLUMN_LIST}
FROM
OrderDetailDeliveryReview
Group By
OrderShipToID,
DeliveryDate,
SKU1
'

DECLARE @column_list AS varchar(max)
SELECT @column_list = COALESCE(@column_list, ',') + 'SUM(Case When Sku2=' + CONVERT(varchar, Sku2) + ' Then Quantity Else 0 End) As [' + CONVERT(varchar, Sku2) + '],' 
FROM OrderDetailDeliveryReview
GROUP BY Sku2
ORDER BY Sku2

Set @column_list = Left(@column_list,Len(@column_list)-1)

SET @template = REPLACE(@template, '{COLUMN_LIST}', @column_list)

EXEC (@template)
2021-05-23