1

我每天都在运行 SQL 查询以生成将在批处理文件中发送的报告。当我运行查询时,在 ActionID 列下有两个可能的值:21 和 33。由于这些值对用户没有任何意义,我想将所有 21 的条目转换为一个字符串,上面写着:已成功移动到:。对于所有 33 的条目,我想将它们转换为表示移动失败的字符串。对于这两个字符串,我希望它位于名为 Comments 而不是 ActionID 的新列下。我有以下代码,但它给了我一些错误。任何人都可以对我的代码进行任何更改以使其成功运行吗?那将不胜感激。

   SELECT  ItemId AS [Item ID],
   CAST(DATEADD(HOUR,-4,CONVERT(DATETIME,LEFT([Date],8)+' '+
    SUBSTRING([Date],10,2)+':'+
    SUBSTRING([Date],12,2)+':'+
    SUBSTRING([Date],14,2)+'.'+
    SUBSTRING([Date],15,3))) AS DATE) 'Date',
   LEFT(CAST(DATEADD(HOUR,-4,CONVERT(DATETIME,LEFT([Date],8)+' '+
    SUBSTRING([Date],10,2)+':'+
    SUBSTRING([Date],12,2)+':'+
    SUBSTRING([Date],14,2)+'.'+
    SUBSTRING([Date],15,3))) AS TIME),8) 'Time',
  [Object] AS [Media],
  SourceSite AS [Source Site], where ActionID = '21' to
  'Was successfully moved to' AS [Comments] AND where ActionID ='33' 'Was  unsuccessful'  AS [Comments],
  DestSite AS [Destination Site]
  FROM (  SELECT  ItemId,
  CONVERT(VARCHAR(18),[Date]) [Date],
  [Object],
  SourceSite,
  DestSite,
        UserCode
  FROM JnlMediumMove
  WHERE CAST(substring(convert(varchar(50), [Date]), 0, 5) + '-' +
  substring(convert(varchar(50), [Date]), 5, 2) + '-' +
  substring(convert(varchar(50), [Date]), 7, 2) AS DATETIME) =
  CONVERT(date, DATEADD(day, -1, getdate()))) A --Converting to date again to remove     the time part
  WHERE UserCode = 'Automation'
  ORDER BY [Date] DESC;
4

1 回答 1

0

您想使用 CASE 语句,基本格式:

CASE WHEN criteria1 THEN result1
     WHEN criteria2 THEN result2
     ELSE default result
END

在您的查询中:

   SELECT  ItemId AS [Item ID],
   CAST(DATEADD(HOUR,-4,CONVERT(DATETIME,LEFT([Date],8)+' '+
    SUBSTRING([Date],10,2)+':'+
    SUBSTRING([Date],12,2)+':'+
    SUBSTRING([Date],14,2)+'.'+
    SUBSTRING([Date],15,3))) AS DATE) 'Date',
   LEFT(CAST(DATEADD(HOUR,-4,CONVERT(DATETIME,LEFT([Date],8)+' '+
    SUBSTRING([Date],10,2)+':'+
    SUBSTRING([Date],12,2)+':'+
    SUBSTRING([Date],14,2)+'.'+
    SUBSTRING([Date],15,3))) AS TIME),8) 'Time',
  [Object] AS [Media],
  SourceSite AS [Source Site], 
  CASE WHEN  ActionID = '21' THEN 'Was successfully moved to' 
       WHEN  ActionID ='33' THEN 'Was  unsuccessful'
       ELSE '' --Optional ELSE
  END  AS [Comments],
  DestSite AS [Destination Site]
  FROM (  SELECT  ItemId,
  CONVERT(VARCHAR(18),[Date]) [Date],
  [Object],
  SourceSite,
  DestSite,
  ActionID,
        UserCode
  FROM JnlMediumMove
  WHERE CAST(substring(convert(varchar(50), [Date]), 0, 5) + '-' +
  substring(convert(varchar(50), [Date]), 5, 2) + '-' +
  substring(convert(varchar(50), [Date]), 7, 2) AS DATETIME) =
  CONVERT(date, DATEADD(day, -1, getdate()))) A --Converting to date again to remove     the time part
  WHERE UserCode = 'Automation'
  ORDER BY [Date] DESC;

编辑:假设您忘记将 ActionID 添加到子查询中。

于 2013-06-26T14:14:36.220 回答