DECLARE @cols AS NVARCHAR(MAX)
DECLARE @query AS NVARCHAR(MAX)
select @cols = '[1015],[1060],[1261],[1373]'
print @cols
set @query = 'SELECT header, ' + @cols + '
from
(
select product_id, header, value
from
(
select
cast(product_id as varchar(100))product_id ,
cast(product_name as varchar(100)) product_name,
cast(product_price as varchar(100)) product_price,
cast(product_weight as varchar(100))product_weight,
cast((select TOP 1 image_name from tblProductImage where tblProductImage.product_id=tblProduct.product_id) as varchar(100)) ProductImage
from tblProduct
) p
unpivot
(
value
for header in (product_name, product_price, product_weight,ProductImage)
) unp
) x
pivot
(
max(value)
for product_id in (' + @cols + ')
) p '
execute(@query)
我正在使用上面的查询及其生成以下输出
现在我的问题是我希望列名称应该是静态的...因为当前最多有5列其中第一列将是标题,这是好的
但是对于列的其余部分我也希望名称应该像Prodcut1,Product2,Product3和Product4。如果只有三个产品,那么它也会显示五列但是对于最后一列,所有属性值都应该为空
答案 0 :(得分:1)
如果我正确理解您的问题,那么当您传递特定的product_id时,您希望列名称为Product1
,Product2
等。
如果这是正确的,那么您可以通过应用row_number()
来创建静态列名称。
您的代码将调整为以下内容:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
DECLARE @prods AS NVARCHAR(MAX)
select @prods = '141,142,143,144'
set @query = 'SELECT header, Product1, Product2, Product3, Product4
from
(
select header, value,
''Product''+cast(row_number() over(partition by header
order by header) as varchar(10)) prods
from
(
select
cast(product_id as varchar(10)) product_id,
product_name,
cast(product_price as varchar(10)) product_price,
product_weight
from tblProduct
where product_id in ('+@prods+')
) p
unpivot
(
value
for header in (product_name, product_price, product_weight, product_id)
) unp
) x
pivot
(
max(value)
for prods in (Product1, Product2, Product3, Product4)
) p '
execute(@query)
见SQL Fiddle with Demo。这给出了结果:
| HEADER | PRODUCT1 | PRODUCT2 | PRODUCT3 | PRODUCT4 |
--------------------------------------------------------------
| product_id | 141 | 142 | 143 | 144 |
| product_name | A141 | A144 | A143 | A142 |
| product_price | 300 | 4000 | 5000 | 200 |
| product_weight | 200gm | 100gm | 400gm | 300gm |