我的数据库记录采用列格式:
ingredient product
Ing1 AAA
Ing1 BBB
Ing2 AAA
Ing2 BBB
... ...
我希望看到格式数据:
product ingredient1 ingredient2
AAA Ing1 Ing2
BBB Ing1 Ing2
select *
from
(
select product, ingredient
from db
) as d
pivot
(
max(ingredient)
for ingredient in ( ingredient1 , ingredient2)
) piv
但此查询返回空ingredient1
和ingredient2
。
答案 0 :(得分:0)
我建议你使用这种类型的查询:
SELECT
product,
MAX(CASE WHEN ingredient = 'Ing1' THEN ingredient END) AS ingredient1,
MAX(CASE WHEN ingredient = 'Ing2' THEN ingredient END) AS ingredient2
FROM
db
GROUP BY
product;
答案 1 :(得分:0)
在PIVOT IN([Ing1], [Ing2])
中,您应该使用值的原始名称,稍后您可以在以下内容中对它们进行别名:
SELECT product,
[Ing1] as [Ingridient1],
[Ing2] as [Ingridient2]
FROM
(
SELECT product, ingredient
FROM #t1
) AS d
PIVOT
(
MAX(ingredient)
FOR ingredient IN ([Ing1], [Ing2])
) piv
您可以在 SQL FIDDLE
查看工作示例答案 2 :(得分:0)
您可以将动态数据透视表编写为:
declare @Finalcollist varchar(max), @collist varchar(max)
declare @sql nvarchar(max)
select @Finalcollist = COALESCE(@Finalcollist + ', ','')
+ QUOTENAME(ingredient) +' AS '
+ Replace (QUOTENAME(ingredient),'Ing','Ingredient')
from
( SELECT DISTINCT ingredient FROM test1) T (ingredient)
select @collist = COALESCE(@collist + ', ','')
+ QUOTENAME(ingredient)
from
( SELECT DISTINCT ingredient FROM test1) T (ingredient)
select @Finalcollist,@collist -- This givesdynamic column list
-- Now setting this @Finalcollist variable in the Dynamic SQL.
set @sql = '
select product, ' + @Finalcollist + '
from
(select product,ingredient from test1
)p
PIVOT(MAX (ingredient) FOR ingredient IN ( ' + @collist + ' )
) AS pvt
ORDER BY product'
--print @sql
EXECUTE sp_executesql @sql
答案 3 :(得分:0)
这里有一些有趣的试用版,你可以拥有尽可能多的Ing,它会增加列数。
CREATE TABLE #temp(ing nvarchar(5), pr nvarchar(5))
INSERT INTO #temp values ('Ing1','AA')
INSERT INTO #temp values ('Ing1','BB')
INSERT INTO #temp values ('Ing2','AA')
INSERT INTO #temp values ('Ing2','BB')
INSERT INTO #temp values ('Ing3','AA')
DECLARE @PivotCols VARCHAR(MAX);
SELECT @PivotCols = COALESCE(@PivotCols + ',','') + QUOTENAME(ing) FROM #temp GROUP BY ing ORDER BY ing
EXEC
(
'SELECT * FROM #temp PIVOT
(
MAX(ing) FOR ing IN (' + @PivotCols + ')
) pvt
')
DROP TABLE #temp
这将导致;
pr Ing1 Ing2 Ing3
----- ----- ----- -----
AA Ing1 Ing2 Ing3
BB Ing1 Ing2 NULL