0

我正在尝试获取一个查询,该查询返回每个 [Measurement Name] 的失败百分比(从现在开始为“失败 %”)。现在,我在下面的查询可以返回特定 SMP(样本)或通配符 SMP 的特定值(输入为 @MEASUREMENT)的失败百分比。

但是,我在编写一个查询时遇到了麻烦,该查询将返回所有测量值的失败百分比,其中失败百分比对于该值是唯一的。问题是,如果@MEASUREMENT 是通配符,我只能让 COUNT 函数计算测量表中的所有失败,所以每个失败都会有相同的失败百分比。

除了使用将测量名称作为主键的表链接到我的其他表的表之外,还有其他方法可以解决此问题吗?(我不认为这对我来说是最佳的,因为会有很多不同的测量名称)

我的数据库表的结构是这样的(仅包括相关的):

表:测量值

列:状态(通过/失败)、SMP ID、名称

DECLARE @SMP varchar(50)
DECLARE @MEASUREMENT varchar(50)

SET @SMP = ''
SET @MEASUREMENT = 'Value 1'

IF(@SMP = '')
    SET @SMP = '%'

IF(@SMP = '%')
    SELECT DISTINCT  
           [Measurements].[Measurement Name], 
            ((CONVERT(float, (SELECT COUNT(*) FROM dbo.[Measurements] 
                WHERE [Status] = 'Fail' AND [Measurement Name] LIKE @MEASUREMENT AND [SMP ID] LIKE @SMP)) / 
            (CONVERT(float, (SELECT COUNT(*) FROM dbo.[Measurements]
                 WHERE [Measurement Name] = @MEASUREMENT AND [SMP ID] LIKE @SMP)))
           )) As [Fail %]
    FROM dbo.[Measurements]
        WHERE [Measurements].[SMP ID] LIKE @SMP
            AND [Measurements].[Measurement Name] LIKE @MEASUREMENT
ELSE
    SELECT DISTINCT [Measurements].[SMP ID], 
           [Measurements].[Measurement Name], 
            ((CONVERT(float, (SELECT COUNT(*) FROM dbo.[Measurements] 
                WHERE [Status] = 'Fail' AND [Measurement Name] LIKE @MEASUREMENT AND [SMP ID] LIKE @SMP)) / 
            (CONVERT(float, (SELECT COUNT(*) FROM dbo.[Measurements]
                 WHERE [Measurement Name] = @MEASUREMENT AND [SMP ID] = @SMP)))
            )) As [Fail %]
    FROM dbo.[Measurements]
        WHERE [Measurements].[SMP ID] LIKE @SMP
            AND [Measurements].[Measurement Name] LIKE @MEASUREMENT
4

1 回答 1

2

看来您需要做的是使用 GROUP BY 子句和 [Measurement Name] GROUP BY。这将为您提供小计,并且您在编写查询时不需要知道 [Measurement Names] 列表是什么。

select 
      [Measurement Name]
    , [SMP ID]
    , [Fail Count] = SUM([Fail])
    , [Not Fail Count] = SUM([Not Fail])
    , [Fail %] = 100 * SUM([Fail]) / SUM(1)
from [Measurements]
cross apply (SELECT [Fail] = case when [Status] = 'Fail' then 1 else 0 end) [X_Fail]
cross apply (SELECT [Not Fail] = case when [Status] <> 'Fail' then 1 else 0 end) [X_Not Fail]
group by [Measurement Name], [SMP ID]

我不确定将 [SMP ID] 放在 select 和 GROUP BY 中,因为我不知道您的模型和数据关系。你可能想放弃它。

于 2013-07-12T14:16:33.907 回答