根据空白列连接列

时间:2019-05-28 10:05:41

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

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

  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];

2 个答案:

答案 0 :(得分:2)

由于同时列出了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];

答案 1 :(得分:1)

您可以使用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];