日期:2014-05-18  浏览次数:20482 次

数据查询 行转列 问题求助
下面是我同事弄的一个脚本,不知道他从哪里弄的(反正他在这方面比我还垃圾,哈哈,而且他已经离职了),这个脚本目的是把行转为列,中间的“else”部分代码是我后来添加的,无论前后,该代码只有第一个数据成功转换了,其余的数据都没有转换。

Select   ([Year]),
max(case   Number   when   1   then   (SmallImageUrl)   else   ( 'defaultMag.jpg ')   end)   as   SmallImageUrl1,
max(case   Number   when   2   then   (SmallImageUrl)   else   ( 'defaultMag.jpg ')   end)   as   SmallImageUrl2,
max(case   Number   when   3   then   (SmallImageUrl)   else   ( 'defaultMag.jpg ')   end)   as   SmallImageUrl3,
max(case   Number   when   4   then   (SmallImageUrl)   else   ( 'defaultMag.jpg ')   end)   as   SmallImageUrl4,
max(case   Number   when   1   then   ( '?ISBN= '   +   ISBN)   else   ( '# ')   end)   as   ISBN1,
max(case   Number   when   2   then   ( '?ISBN= '   +   ISBN)   else   ( '# ')   end)   as   ISBN2,
max(case   Number   when   3   then   ( '?ISBN= '   +   ISBN)   else   ( '# ')   end)   as   ISBN3,
max(case   Number   when   4   then   ( '?ISBN= '   +   ISBN)   else   ( '# ')   end)   as   ISBN4,
max(case   Number   when   1   then   (IssueName)   else   ( '(无杂志) ')   end)   as   IssueName1,
max(case   Number   when   2   then   (IssueName)   else   ( '(无杂志) ')   end)   as   IssueName2,
max(case   Number   when   3   then   (IssueName)   else   ( '(无杂志) ')   end)   as   IssueName3,
max(case   Number   when   4   then   (IssueName)   else   ( '(无杂志) ')   end)   as   IssueName4  
From  
MagazineIssue  
Where   OwnerEMNumber   =   @ISBN
group   by   [Year]


------解决方案--------------------
确实错了.为何有3次等于1,2,3,4?
------解决方案--------------------
是哪个结果显示出来的

------解决方案--------------------
这样改试试看,不过要确保,SmallImageUrl和IssueName字段的第一个字符不为空格。
Select ([Year]),
ltrim(max(case Number when 1 then (SmallImageUrl) else ( ' defaultMag.jpg ') end)) as SmallImageUrl1,
ltrim(max(case Number when 2 then (SmallImageUrl) else ( ' defaultMag.jpg ') end)) as SmallImageUrl2,
ltrim(max(case Number when 3 then (SmallImageUrl) else ( ' defaultMag.jpg ') end)) as SmallImageUrl3,
ltrim(max(case Number when 4 then (SmallImageUrl) else ( ' defaultMag.jpg ') end)) as SmallImageUrl4,
ltrim(max(case Number when 1 then ( '?ISBN= ' + ISBN) else ( ' # ') end)) as ISBN1,
ltrim(max(case Number when 2 then ( '?ISBN= ' + ISBN) else ( ' # ') end)) as ISBN2,
ltrim(max(case Number when 3 then ( '?ISBN= ' + ISBN) else ( ' # ') end)) as ISBN3,
ltrim(max(case Number when 4 then ( '?ISBN= ' + ISBN) else ( ' # ') end)) as ISBN4,
ltrim(max(case Number when 1 then (IssueName) else ( ' (无杂志) ') end)) as IssueName1,
ltrim(max(case Number when 2 then (IssueName) else ( ' (无杂志) ') end)) as IssueName2,
ltrim(max(case Number when 3 then (IssueName) else ( ' (无杂志) ') end)) as IssueName3,
ltrim(max(case Number when 4 then (IssueN