【问题标题】:concatenate columns based on blank columns基于空白列连接列
【发布时间】:2019-05-28 10:05:41
【问题描述】:

我有三列,- 和 / 应该用作分隔符结果应该出现在新列中(文件索引-子索引/年),如果子索引为空,那么结果应该是(文件索引/年)。

  SELECT 
[ File Index].[File Index]
, [ File Index].[Sub Index]
, [ File Index].[Financial Year]
, [ File Index].[File Index] & [Sub Index] & [Financial Year] AS [Composite Index]
  FROM [File Index];

【问题讨论】:

  • 您使用的是 MySQL 还是 MS Access?

标签: sql ms-access ms-office ms-access-2013


【解决方案1】:

由于您同时列出了 MySQLMS Access,因此这里提供了两者的解决方案。

对于MySQL,您可以为此使用CASE 语句:

SELECT [File Index], [Sub Index], [Financial Year],
       CASE WHEN [Sub Index] IS NOT NULL 
             THEN Concat([File Index], '-', [Sub Index], '/', [Financial Year]) 
             ELSE Concat([File Index], '/', [Financial Year]) 
       END as [Composite Index] 
FROM [File Index];

对于MS Access,您将使用Switch(...)

SELECT [File Index], [Sub Index], [Financial Year],
       Switch(Not IsNull([Sub Index]), 
                 [File Index] & '-' & [Sub Index] & '/' & [Financial Year],
              IsNull([Sub Index]), 
                 [File Index] & '/' & [Financial Year]
       ) as [Composite Index] 
FROM [File Index];

【讨论】:

    【解决方案2】:

    您可以使用 IIF 函数:IIF(Condition;ConcatenationIfTrue;ConcatenationIfFalse)

      SELECT 
    [ File Index].[File Index]
    , [ File Index].[Sub Index]
    , [ File Index].[Financial Year]
    , IIF(ISNULL([Sub Index];[ File Index].[File Index] & "/" & [Financial Year];[ File Index].[File Index] & [Sub Index] & [Financial Year]) AS [Composite Index]
      FROM [File Index];
    

    【讨论】:

      猜你喜欢
      • 2017-12-15
      • 2019-02-04
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      • 2022-01-20
      • 2017-02-10
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多