--测试数据
DROP TABLE #Temp
CREATE TABLE #Temp
(
TypeClass NVARCHAR(200),
Name NVARCHAR(200),
Price int
)
INSERT INTO #Temp (TypeClass ,Name ,Price)
VALUES ('白班', 'A' ,10)
INSERT INTO #Temp (TypeClass ,Name ,Price)
VALUES ( '晚班' ,'A' ,20)
INSERT INTO #Temp (TypeClass ,Name ,Price)
VALUES ('白班', 'B' ,100)
INSERT INTO #Temp (TypeClass ,Name ,Price)
VALUES ( '晚班' ,'B' ,200)/*
相要达到的效果
TypeClass会有很多,不只是白班晚班还有其它,用于也会有很多用户
===================
用户 白班 晚班
A 10 20
B 100 200
*/
解决方案 »
- 怎么样动态传参数到存储过程?
- 在线急等!请各位高手大哥帮忙看看!![Microsoft][ODBC SQL Server Driver][SQL Server]从字符串转换为 smalldatetime 数据类型时发生语
- 高分求数据库多用户问题
- 请问我想在insert触发器里写一个SQL语句,能不能获取到底是哪个机器或客户端在向这个表插入数据呢
- 这个问题有点小麻烦!
- 公司想做一套b/s的销售管理和统计系统,请各位大虾报价
- 请指导一个关联查询,谢谢!
- 如何得到和最大的5条连续记录!
- sql 问题请指教
- 对于局部变量,text、ntext 和 image 数据类型无效
- 推荐系统新手小白求助大神
- codefirst迁移数据库的时候报错
max(case when TypeClass='白班' then price else 0 end)as 白班,
max(case when TypeClass='晚班' then price else 0 end)as 晚班
from #temp
group by name
--固定
SELECT * FROM #Temp
PIVOT
(
SUM(Price)
FOR TypeClass IN([白班],[晚班])
)P--动态
DECLARE @Sql VARCHAR(max)=''SELECT @Sql=@Sql+',' +QUOTENAME(TypeClass) from (SELECT DISTINCT TypeClass FROM #Temp ) ASET @Sql='
SELECT * FROM #Temp
PIVOT
(
SUM(Price)
FOR TypeClass IN('+STUFF(@Sql,1,1,'')+')
)P'EXEC(@Sql)
CREATE TABLE #Temp
(
TypeClass NVARCHAR(200),
Name NVARCHAR(200),
Price int
)
INSERT INTO #Temp (TypeClass ,Name ,Price)
VALUES ('白班', 'A' ,10)
INSERT INTO #Temp (TypeClass ,Name ,Price)
VALUES ( '晚班' ,'A' ,20)
INSERT INTO #Temp (TypeClass ,Name ,Price)
VALUES ('白班', 'B' ,100)
INSERT INTO #Temp (TypeClass ,Name ,Price)
VALUES ( '晚班' ,'B' ,200)
/*
相要达到的效果
TypeClass会有很多,不只是白班晚班还有其它,用于也会有很多用户
===================
用户 白班 晚班
A 10 20
B 100 200
*/
select *
from (select Name,typeClass,price from #Temp) as infotest
pivot(sum(price) for typeClass in([白班],[晚班]))as lie
GO
from (select Name,typeClass,price from #Temp) as Table1
pivot(sum(price) for typeClass in([白班],[晚班]))as column1
GO
pivot(sum(price) for typeclass in([白班],[晚班])) as c