drop table #Tmp --删除临时表#Tmp
create table #Tmp --创建临时表#Tmp
(
ID int not null, --创建列ID,并且每次新增一条记录就会加1
Temp_NAME varchar(50),
AMOUNT money
);
insert into #tmp
Select 1 ,'A', 2 union all
Select 2 ,'A', 3 union all
Select 3 ,'B', 20 union all
Select 4 ,'C', 6 union all
Select 5 ,'C', 19
--1 原始的
select * from #tmp
--2 筛选的
select Temp_NAME,AMOUNT from #tmp a
WHERE ID=(SELECT max(ID) FROM #tmp WHERE Temp_NAME=a.Temp_NAME)
--3 行转列的
Select
max(case Temp_NAME when 'A' then AMOUNT else 0 end) [A] ,
max(case Temp_NAME when 'B' then AMOUNT else 0 end) [B] ,
max(case Temp_NAME when 'C' then AMOUNT else 0 end) [C]
from (select Temp_NAME,AMOUNT from #tmp a
WHERE ID=(SELECT max(ID) FROM #tmp WHERE Temp_NAME=a.Temp_NAME)
) As T group by AMOUNT
---4 pivot 的
select * from
(select Temp_NAME,AMOUNT from #tmp a
WHERE ID=(SELECT max(ID) FROM #tmp WHERE Temp_NAME=a.Temp_NAME)
) As T pivot(max(AMOUNT)for Temp_NAME in(A,B,C)) a