读书人

Group by 空行时默以为不空的结果一起

发布时间: 2013-11-13 14:04:18 作者: rapoo

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 - 1)
else t.eag end as eag
from test t
)a
group by a.eag;

不好意思 多了一杠\ 去掉

如果两个空行呢?你这个只能是一行啊



这是肯定的,你必须要把空行更新掉,两个空行的话 ,第二个空行查的前面的一行为空

读书人网 >asp.net

热点推荐