日期:2014-05-17  浏览次数:20627 次

Group by 空行时默认为不空的结果一起group by
表结构:
id   eag
1    男
2    
3    女
4    
5    男
6    男
7    
8    女

表中数据类似于这样    ,第2、4、7行都为空 ,没有数据  
如何在查询时   在group by后 第2行的跟第一行为一组  第4行的跟第3行的一组  第7行的跟5、6行一组
,也就是 查询语句 默认eag为空的跟上一个id归一组  

------解决方案--------------------
如果是sqlserver,用case...when语句,对null值得记录去取上一个id对应的值
case eag when null then select eag where id=id-1(如果id是顺序加一的话) 
或写个存储过程或者写代码逐条处理一下

------解决方案--------------------
group by isnull(x.eag,select eag from t where id=id-1)
------解决方案--------------------
引用:
引用
group by isnull(x.eag,select eag from t where id=id-1)  

x.是什么?
group by isnull(eag,select eag from t where id=id-1)   他这里写的是指表; isnull(列名,取代值)
------解决方案--------------------
select t1.id, (select top 1 eag from tab where id < t1.id order by id desc)
  from tab t1
 where t1.eag is null
union all
select id, eag from tab where eag is not null


组合成上面的数据在分组
手打,错了,改改

如果在MSSQL中(select top 1 eag from tab where id < t1.id order by id desc) 不行
你就Left join
------解决方案--------------------
引用:
引用
如果是sqlserver,用case...when语句,对null值得记录去取上一个id对应的值
case eag when null then select eag where id=id-1(如果id是顺序加一的话) 
查找出来的全是空 这是为什么

     select a.eag as 性别, count(1) as 数量 
from (
select case 
when t.eag is null then (select eag from test t1 where t1.id = t.id - 1) \
else t.eag end as eag 
from test t
      )a 
group by a.eag;

------解决方案--------------------
引用:
Quote: 引用:


select a.eag as 性别, count(1) as 数量 
from (
select case 
when t.eag is null then (select eag from test t1 where t1.id = t.id&nb