求SQL语言(同一列数据分成2列显示)(100分)

  • 主题发起人 主题发起人 kuaishang
  • 开始时间 开始时间
K

kuaishang

Unregistered / Unconfirmed
GUEST, unregistred user!
数据库表中有“分组号”这一列:我需要分成2列显示:0为一列,其余为一列,然后对这列进行比较,当分组号发生变化时,给个标识(用“—”表示):<br>&nbsp; &nbsp;分组号:<br>&nbsp; &nbsp; 0<br>&nbsp; &nbsp; 0<br>&nbsp; &nbsp; 1<br>&nbsp; &nbsp; 1<br>&nbsp; &nbsp; 0<br>&nbsp; &nbsp; 0<br>&nbsp; &nbsp; 2<br>分成: 分组号1: &nbsp;分组号2: &nbsp; 标识:<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2 &nbsp; &nbsp; &nbsp; &nbsp;-<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0
 
一句话不容易实现。
 
没看明白题目啥意思
 
你的意思是<br>第一行数据 0 &nbsp;1<br>第二行数据 0 &nbsp;1<br>...<br>你是要比较什么?和零比较吗?<br>做什么用
 
0那行不需要比较,需要比较的是第二列:<br>&nbsp; &nbsp;分组号:<br>&nbsp; &nbsp; 0<br>&nbsp; &nbsp; 1<br>&nbsp; &nbsp; 1<br>&nbsp; &nbsp; 0<br>&nbsp; &nbsp; 0<br>&nbsp; &nbsp; 2<br>&nbsp; &nbsp; 0<br>&nbsp; &nbsp; 3<br>分成2列显示:<br>&nbsp; &nbsp; &nbsp; 分组号1: &nbsp;分组号2: &nbsp; 标识:<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;1<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2 &nbsp; &nbsp; &nbsp; &nbsp;-<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;0 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;3 &nbsp; &nbsp; &nbsp; &nbsp;-<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 3
 
你要用一个SQL语句把结果取到一个数据集里吗?列就是分组号1,分组2,标识?<br>如果是的话我建议你做个程序判断吧,比用一个SQL语句简单明了多了
 
你是不是要这样的结果啊:<br>&nbsp;select 分组号1,分组号2,case when 分组号1&lt;&gt;分组号2 then '-' end 标识 from &nbsp;(select case when isnull(分组号,0)=0 then 分组号 end 分组号1,case when isnull(分组号,0)&lt;&gt;0 then 分组号 end 分组号2 from 表) a
 
谢谢,我先测试,我只用报表啊,不用到程序,看看SQL能否实现
 
select identity(int,1,1) id,分组号,'分组号1' 列名 into #a from table1 where 分组号=0<br><br><br>select identity(int,1,1) id,分组号,'分组号2' 列名 into #b from table1 where 分组号&lt;&gt;0<br><br><br>declare &nbsp; @sql &nbsp; varchar(8000),@sql1 varchar(8000)<br>set @sql1='select id '<br>select &nbsp; @sql1=@sql1+',sum(case &nbsp; when &nbsp; 列名='''+列名+''' &nbsp; then &nbsp; 分组号 &nbsp; else &nbsp;null &nbsp;end) &nbsp; as &nbsp; '+列名 from &nbsp; <br><br>(select * from #a<br>union all<br>select * from #b) a &nbsp;group &nbsp; by &nbsp; 列名 &nbsp;<br><br>set &nbsp; @sql=@sql1+ &nbsp;' into ##c from &nbsp;(select * from #a<br>union all<br>select * from #b) a group &nbsp; by &nbsp;id ' &nbsp; <br><br><br>exec(@sql) &nbsp;<br><br>select a.分组号1,a.分组号2,case when a.id=b.id and a.id&lt;&gt;1 then '-' else '' end 标识 from ##c a<br>left join (select min(id) id,分组号1,分组号2 from ##c group by 分组号1,分组号2) b<br>on a.分组号1=b.分组号1 and a.分组号2=b.分组号2<br><br>drop table #a,#b,##c
 
报表可以实现分列,不用这么麻烦
 
谢谢迷途的羔羊,SQL语言能够达到要求!!!
 
请问iKing:报表怎么样才可以<br>可以实现分列?
 
后退
顶部