如何选择一列中的唯一值并按不同列进行分组

问题描述 投票:0回答:1

我在 Oracle 中有一个表,其架构如下所示

我想获得结果部分所示的输出。知道 Oracle 中的 WHERE 子句应该是什么样子才能获得我需要的输出吗?

Table

col1_string_primary_key col2_number   col3_string              col4_timestamp
-----------------------------------------------------------------------------
                  11-11           1          str1         2024/09/04 00:00:00
                  22-22           2          str2         2024/09/04 00:01:00
                  33-33           1          str1         2024/09/04 00:02:00
                  44-44           4          str4         2024/09/04 00:03:00
                  55-55           1          str7         2024/09/04 00:04:00
                  44-44           2          str3         2024/09/04 00:04:00
                  55-55           1          str1         2024/09/04 00:00:01


Desired Query?

select 
  col2_number, col3_string
from 
  table
where 
      col4_timestamp >= to_timestamp('2024-09-04 00:00:00', 'YYYY-MM-DD HH24:MI:SS') 
  AND col4_timestamp  < to_timestamp('2024-09-04 00:05:00', 'YYYY-MM-DD HH24:MI:SS')


Desired Result

col2_number col3_string
-----------------------
          1   str1,str3
          2        str2
          4        str4
sql oracle plsql
1个回答
0
投票

那个看起来像一个

listagg
函数问题,但是......期望的结果与样本数据并不真正匹配,因为

  • 仅通过查看您发布的信息,我并没有完全得到您想要的信息(
    where
    子句不会过滤任何内容,它会返回您发布的所有行),或者
  • 你忘了真正解释从源到目标的规则

无论如何,这里有一个您可能感兴趣的选项,看看它是否有帮助。

样本数据:

SQL> with test (pk, col2, col3, col4) as
  2    (select '11-11', 1, 'str1', to_date('2024/09/04 00:00', 'yyyy/mm/dd hh24:Mi') from dual union all
  3     select '22-22', 2, 'str2', to_date('2024/09/04 00:01', 'yyyy/mm/dd hh24:mi') from dual union all
  4     select '33-33', 1, 'str2', to_date('2024/09/04 00:02', 'yyyy/mm/dd hh24:mi') from dual union all
  5     select '44-44', 4, 'str4', to_date('2024/09/04 00:03', 'yyyy/mm/dd hh24:mi') from dual union all
  6     select '55-55', 1, 'str7', to_date('2024/09/04 00:04', 'yyyy/mm/dd hh24:mi') from dual union all
  7     select '44-44', 2, 'str3', to_date('2024/09/04 00:04', 'yyyy/mm/dd hh24:mi') from dual union all
  8     select '55-55', 1, 'str1', to_date('2024/09/04 00:01', 'yyyy/mm/dd hh24:mi') from dual
  9    )

查询从这里开始:

 10  select col2, listagg(distinct col3, ', ') within group (order by col3) col3
 11  from test
 12  where col4 >= to_date('2024/09/04 00:00', 'yyyy/mm/dd hh24:mi')
 13    and col4 <  to_date('2024/09/04 00:05', 'yyyy/mm/dd hh24:mi')
 14  group by col2;

      COL2 COL3
---------- --------------------
         1 str1, str2, str7
         2 str2, str3
         4 str4

SQL>
© www.soinside.com 2019 - 2024. All rights reserved.