27,579
社区成员
发帖
与我相关
我的任务
分享
--> 测试数据:#
if object_id('tempdb.dbo.#') is not null drop table #
create table #(fname varchar(8), ftype varchar(8), fvalue varchar(8))
insert into #
select '小乔', '早餐', '10块' union all
select '小乔', '中餐', '20块' union all
select '小乔', '晚餐', '5块' union all
select '大乔', '早餐', '15块' union all
select '大乔', '中餐', '5块' union all
select '大乔', '晚餐', '10块'
select fname,
早餐=max(case ftype when '早餐' then fvalue end),
中餐=max(case ftype when '中餐' then fvalue end),
晚餐=max(case ftype when '晚餐' then fvalue end)
from # group by fname
/*
fname 早餐 中餐 晚餐
-------- -------- -------- --------
大乔 15块 5块 10块
小乔 10块 20块 5块
*/
---语法没有问题,数据类型转化一下就可以了。
---把每个cast(Fvalue as int)不就可以吗
select Fname,
max(case Ftype when '早餐'then cast(Fvalue as int) else 0 end) as '早餐',
max(case Ftype when '中餐' then cast(Fvalue as int) else 0 end) as '中餐',
max(case Ftype when '晚餐' then cast(Fvalue as int) else 0 end)
as '晚餐'from case_table
group by Fname
---语法没有问题,数据类型转化一下就可以了。
---把每个cast(Fvalue as int)不就可以吗
select Fname,
sum(case Ftype when '早餐'then cast(Fvalue as int) else 0 end) as '早餐',
sum(case Ftype when '中餐' then cast(Fvalue as int) else 0 end) as '中餐',
sum(case Ftype when '晚餐' then cast(Fvalue as int) else 0 end)
as '晚餐'from case_table
group by Fname