【问题标题】:Group by one column and substring of its own按一列和自己的子字符串分组
【发布时间】:2015-03-21 11:43:21
【问题描述】:

无法为我的问题编写 Sql。 我有一个包含 2 列项目代码和到期日期的表格。

Itemcode.       Expiration
Abc123.         2014-08-08
Abc234.         2014-07-07
Cfg345.         2014-06-06
Cfg567.         2014-07-08

输出应基于项目代码的前 3 位数字和最短到期日期,如下所示

Abc.     2014-07-07.    Abc234
Cfg.     2014-06-06.    Cfg345

谢谢

编辑: 查询是这样的,它实际上是连接多个表以获取项目代码和到期时间。 选择 substr(y.itemcode,1,3), min(x.expiration_date) 到期, y.itemcode
从 X x, Y y 其中 y.id = x.id

                          and x.number  in 
                              (select number from xyz 
                                where id = x.id
                                and codec in ('C', 'M', 'T', 'H')

                               ) 

                               group by substr(y.itemcode,1,3), y.itemcode

【问题讨论】:

  • 显示您的代码。你已经尝试了什么?
  • 我无法弄清楚。我使用了 group by 子句,但我需要子字符串和项目代码,因此使用 group by 没有帮助。请帮忙。

标签: sql


【解决方案1】:

我不熟悉“m”。这是一个 ANSI 标准的 SQL 解决方案:

select substring(itemcode, 1, 3), expiration, itemcode
from (select t.*,
             row_number() over (partition by substring(itemcode, 1, 3)
                                order by expiration desc
                               ) as seqnum
      from table t
     ) t
where seqnum = 1;

大多数数据库都支持此功能。有些名称可能略有不同(例如substr()left() 用于子字符串操作)。

【讨论】:

  • HI Gordon 我已经修改了我的问题并提供了确切的查询。我需要你的帮助,因为我无法把它放在那里。它连接 2 个表以获取数据。请帮忙。
猜你喜欢
  • 2012-07-15
  • 1970-01-01
  • 2014-02-07
  • 2011-11-20
  • 2017-10-13
  • 2017-01-13
  • 2014-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多