【问题标题】:how to ignore specific values in group by in sql如何在sql中忽略group by中的特定值
【发布时间】:2013-07-10 15:24:25
【问题描述】:

所以我提出的查询:

    select distinct id, str_replace(convert(varchar,start_time,102),'.','-') [date], 
    min(convert(varchar(8), start_time, 108)) [start time],
    max(convert(varchar(8), start_time, 108)) [end time],
    max(o) [o],
    max(a) [a], case when error_msg != '(null)' then error_msg end [error?],
    from table group by id order by id desc

带回这个:

   id     date      start time   end time   o   a   error?
------------------------------------------------------------     
7338971 2012-06-09  11:06:20    11:06:20    2   5   (null)
7338970 2012-06-09  11:06:08    11:06:59    362 725 Yes
7338970 2012-06-09  11:06:08    11:06:59    362 725 (null)

其中数据按 id 分组。但是,id# 7338970 有两个条目,因为有一个空值和一个实际错误。有什么办法可以忽略null,只显示一行7338970,错误列显示yes? 所以它会是:

    id     date      start time   end time   o   a   error?
------------------------------------------------------------     
7338971 2012-06-09  11:06:20    11:06:20    2   5   (null)
7338970 2012-06-09  11:06:08    11:06:59    362 725 Yes

提前致谢

【问题讨论】:

  • 请发布原始 SQL 查询。
  • 您使用的是什么 rdbms?如果一个 ID 只有一行,无论它的错误是否为空,您都想查看它吗?
  • 我使用的是 sybase 5.5,是的,我想看看它是否为空

标签: sql null group-by


【解决方案1】:

尝试添加:

and error is not null

您的查询。

【讨论】:

  • 我想看看错误是否为空,但如果 id 不存在错误
【解决方案2】:

基于注释“如果错误为空,那么它应该在错误列中显示空”:

select distinct id, str_replace(convert(varchar,start_time,102),'.','-') [date], 
min(convert(varchar(8), start_time, 108)) [start time],
max(convert(varchar(8), start_time, 108)) [end time],
max(o) [o],
max(a) [a], case when error_msg != '(null)' then isnull(error_msg,'null') end [error?],
from table 
group by id order by id desc

【讨论】:

  • 如果文件的行程没有错误,我想看看错误是否为空。
  • 我不明白你在说什么。 “if there error is null if there is no error”是什么意思?
  • 如果error为null,那么error列应该显示null,而不是完全排除
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多