如何重命名一些条件的查询结果

问题描述 投票:-2回答:4

由于我的查询的结果,我有一个3倍的值。我需要缩写和返回的列值。对于如。说我的结果是世界贸易中心,我需要它来打印为WTC

sql oracle
4个回答
0
投票

您可以使用此case表达式:

select (case when col = 'World Trade Center' then 'WTC'
             . . .
         end) as abbrev

需要这样的事情竟然会暗示你想要无论什么实体,这是一个参考表。您可能会发现多个查询最终会做同样的事情 - 然后,如果增加了第四值,大量的代码需要改变。


0
投票

这是我刚为你做,它的工作原理SQL Server上的罚款,如果你用别的也许你将不得不改变小事情,但它不应该是困难的。请记住,改变VARCHAR大小以适合你的数据库的专栏。

DECLARE @return VARCHAR(30)
DECLARE @loop INT
DECLARE @myString VARCHAR(30)

SET @return = '' -- The variable that will be returned
SET @myString = 'World Trade Center' -- Your original value
SET @loop = LEN(@myString) - LEN(REPLACE(@myString,' ','')) + 1 -- Calculate the    nombre of spaces to know how many times to loop

DECLARE @count INT = 1;

WHILE @count <= @loop -- While u haven't parsed all words of the original string
BEGIN
   SET @return = SUBSTRING(PARSENAME(REPLACE(@myString, ' ', '.'), @count), 1, 1) + @return -- Add the first letter of each word to the return variable
   SET @count = @count + 1;
END;

SELECT @return -- And there you got 'WTC', you can use it as you want

每个单词返回:可能看起来很奇怪,因为它看起来像它会以相反的顺序添加字母的第一个字母的增加,但实际上工作正常一样,至少在SQL Server上


0
投票

如何正则表达式的一点点?

SQL> with test (col) as
  2    (select 'World Trade Centre ' from dual union all
  3     select 'Additional Voluntary Contribution' from dual union all
  4     select 'Executive Pension Plan' from dual union all
  5     select 'Money Purchase Plan' from dual
  6    )
  7  select
  8    col,
  9    listagg(substr(regexp_substr(col, '\w+', 1, column_value), 1, 1), '')
 10      within group (order by column_value) result
 11  from test,
 12       table(cast(multiset(select level from dual
 13                           connect by level <= regexp_count(col, ' ') + 1
 14                          ) as sys.odcinumberlist))
 15  group by col;

COL                               RESULT
--------------------------------- ----------
Additional Voluntary Contribution AVC
Executive Pension Plan            EPP
Money Purchase Plan               MPP
World Trade Centre                WTC

SQL>

它有什么作用?

  • 拆分每串入行(这是9所做REGEXP_SUBSTR一致)
  • 选择每一个字符串的第一个字母(这是9所做SUBSTR一致)
  • 聚合这些首字母到结果(这是LISTAGG做什么)

0
投票

我不知道什么地方有错在先的,什么是我现在要做的。但我已经使用CASE表达式的尝试,现在它的工作。感谢所有为您的输入。

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