合并记录并显示在不同的列中

时间:2016-03-22 10:38:37

标签: sql sql-server tsql

我写了一个SQL,它给了我一个数据集。

    SELECT [Id]
      --,s1.[CustomerId]
      ,[Date]
      ,dc.ColumnName
      ,dc.ColumnId
      ,[RuleId]
     -- ,[RuleExceptionCount]
      --,[TotalRowCount]
      ,CAST((TotalRowCount - RuleExceptionCount)/CAST(TotalRowCount AS FLOAT) * 100 AS DECIMAL(6,2)) AS [FailurePercentage]
  FROM [ASMPredictiveAnalytics].[dbo].[DQHistory] AS s1
  JOIN dbo.DQColumns dc ON dc.ColumnId = s1.ColumnId
  WHERE Date = (SELECT MAX(date)  FROM
  dbo.DQHistory) AND s1.CustomerId=@CustomerId

结果如下所示

Looks right now

我希望结果看起来像这样

[Want to make it this way[2]

通过添加另一个名为“Quality”的列,基本上将“Summary”和“Resolution notes”的记录转换为单个记录,对于其他“Columnnames”,需要将“Quality”显示为“N /一个”。

1 个答案:

答案 0 :(得分:1)

您应该修改您的查询,如下所示:

SELECT 
     MIN([Id]) as [Id],
     [Date],
     [ColumnName],
     [ColumnId], 
     COALESCE(CAST(MIN(FailurePercentage) as varchar),'N/A') as FailurePercentage,
     COALESCE(cast(MIN(Quality) as varchar),'N/A') as Quality
 FROM
   (SELECT 
              [Id]
              --,s1.[CustomerId]
              ,[Date]
              ,ColumnName
              ,ColumnId
              -- ,[RuleExceptionCount]
              --,[TotalRowCount] 
              ,CASE WHEN [RuleId]=1 THEN CAST((TotalRowCount - RuleExceptionCount)/CAST(TotalRowCount AS FLOAT) * 100 AS DECIMAL(6,2)) ELSE NULL END as [FailurePercentage]
              ,CASE WHEN [RuleId]=2 THEN CAST((TotalRowCount - RuleExceptionCount)/CAST(TotalRowCount AS FLOAT) * 100 AS DECIMAL(6,2)) ELSE NULL END as [Quality] 
       FROM [ASMPredictiveAnalytics].[dbo].[DQHistory] AS s1
        JOIN dbo.DQColumns dc ON dc.ColumnId = s1.ColumnId
        WHERE Date = (SELECT MAX(date)  FROM
        dbo.DQHistory) AND s1.CustomerId=@CustomerId
    ) T
    GROUP BY [Date],[ColumnName],[ColumnId]

<强>解释

由于您对故障百分比和质量进行了相同的计算,因此我将它们放在内部查询中,但其中一个基于RuleId列的值为NULL。

在外部查询中,我们只是简单地对所有内容进行分组并计算MIN(您可以在此处使用任何聚合函数)而不是NULL值,并将该值替换为'N/A'以防它NULL app.filter('dateUTC', function ($filter) { return function (input, format) { if (!angular.isDefined(format)) { format = 'dd/MM/yyyy'; } var date = new Date(input); return $filter('date')(date.toISOString().slice(0, 23), format); }; }); 1}}