如何使用SQL查询更改正在显示的数据

时间:2013-06-26 14:12:47

标签: sql sql-server

我每天都在运行一个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;

1 个答案:

答案 0 :(得分: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添加到子查询中。