SQL查询结果横向显示
第一张表S,车类型表
第二张表C,姓名表
第三张表SC,两个表的关系还有价格
我把他们加在一个视图里面。视图代码
SELECT dbo.s.id AS s_id, dbo.c.id AS c_id, dbo.c.name AS c_name, dbo.s.name AS s_name, dbo.sc.sMoney
FROM dbo.c INNER JOIN
dbo.sc ON dbo.c.id = dbo.sc.c_id INNER JOIN
dbo.s ON dbo.sc.s_id = dbo.s.id
要显示的结果
SQL的语句。
declare @sql varchar(8000)
set @sql = 'select c_name as 姓名 '
select @sql = @sql + ' , max(case s_name when ''' + s_name + ''' then sMoney else null end) [' + s_name + ']'
from (select distinct s_name from scall) as a
set @sql = @sql + ' from scall group by c_name'
exec(@sql)