我正在尝试透视表并将结果显示在1条记录中。这一切都有效,如果没有PK字段,但有一个,我没有得到所需的结果。您可以使用以下语句进行测试。
Create table #Test
(id int identity(1,1), item_name varchar(50),item_value varchar(50), decode float )
insert into #Test (item_name, item_value, decode)
values ('Threshold', 'GROWTH', 0.6),
('Threshold', 'LEVERAGE', 0.4)
Select pvt.* from #Test d
Pivot (
max(d.decode)
for d.item_value in (Growth,Leverage)
) as pvt
where item_name = 'Threshold'
drop table #test
此查询的结果是
| id | item_name | Growth | Leverage
1 Threshold 0.6 NULL
2 Threshold NULL 0.4
我想要的结果
item_name | Growth | Leverage
Threshold 0.6 0.4
如果从create语句中删除Identity列,我可以实现我正在寻找的结果,但我不能这样做,因为我使用的是真正的表。如何进行查询并绕过' id列并实现我想要的结果
答案 0 :(得分:1)
由于PK对于每一行都是唯一的(标识),因此您需要将其从查询中排除,否则它将包含在PIVOT的分组方面。要解决这个问题,您需要使用子查询来仅选择PIVOT所需的列。
将您的查询更改为以下内容:
Select item_name, Growth,Leverage
from
(
select item_name, item_value, decode
from #Test
where item_name = 'Threshold'
) d
Pivot
(
max(d.decode)
for d.item_value in (Growth,Leverage)
) as pvt;
见Demo。
答案 1 :(得分:1)
另一种选择是使用交叉表而不是PIVOT。
select item_name
,MAX(case when item_value = 'Growth' then decode end) as Growth
, MAX(case when item_value = 'Leverage' then decode end) as Leverage
from #Test
where item_name = 'Threshold'
group by item_name
答案 2 :(得分:1)
;WITH CTE AS
(Select d.*,
ROW_NUMBER()OVER(PARTITION BY
item_name ORDER BY item_name DESC )rn
from #Test d)
Select item_name,
Growth,
Leverage
FROM
(select item_name, item_value, decode
from CTE
where item_name = 'Threshold' )d
Pivot (
max(d.decode)
for d.item_value in (Growth,Leverage)
) as pvt