计算一列中的唯一结果,该列在另一列中具有给定值

时间:2013-12-10 09:54:27

标签: sql sql-server

我目前正在使用产品测试数据库。每个经过测试的设备都有一个唯一的标识符,一个日期时间戳和一批测试,每个测试都有一个结果。最终测试被命名为“已完成”,通过或失败反映了整个批次。

我正在尝试在SQL Server 2008中编写一个查询,它会计算出第一次通过的设备数量,按日期分组。

将我的结果限制在11月以后,我可以列出每个设备的测试次数:

SELECT UID, COUNT (UID) AS Attempts
FROM [dbase].[dbo].[tbl_results]
where TestName = 'Finished'
  and Stamp > '2013-11-01'
GROUP BY UID
ORDER BY Attempts

然而,这并没有给我一个计数,按日期分组,或任何想法该批次是通过还是失败。在我的第一次尝试中,我包括“Where Pass ='P'”,但后来意识到只是排除了所有导致错误信息的失败。

我认为我需要找到一种方法让这个查询只显示Attempts = 1(带有子查询?)的产品,然后将结果表连接到输出并计算Pass ='P',但我不能弄清楚join命令的语法。

我不是在寻找代码 - 我更愿意有人可以给我一些建议。我只使用SQL大约两天......请有人帮我一把吗?

谢谢!

汤姆

示例数据:

UID         Pass    TestName    Stamp
97292       P       Finished    02/12/2013 07:43
97567       F       Finished    03/12/2013 13:21
97567       P       Finished    03/12/2013 13:25
97568       P       Finished    03/12/2013 12:42
97569       P       Finished    03/12/2013 12:28
97570       P       Finished    03/12/2013 11:56
97571       F       Finished    03/12/2013 11:40
97571       P       Finished    03/12/2013 11:44
97572       F       Finished    03/12/2013 11:23

此数据已由UID订购 - 它显示第一次传递97292(单个结果,值P),第二次传递97567(两个结果,P和F),而97572仅测试一次但失败。

理想输出:

Date        Passed First Time
02/12/2013  45
03/12/2013  37
04/12/2013  62

2 个答案:

答案 0 :(得分:0)

只有一次尝试的产品的子查询可能如下所示:

Select UID 
from tbl_results
Where TestName='Finished'
Group by UID
Having Count(*)=1

子查询可以使用别名与tbl_results连接,并通过UID连接,过滤为Testname,Pass和DateStamp。
对于分组,您必须从Stamp中提取datepart: 在SQL-Server 2008 +上,您可以使用CONVERT (STAMP, GETDATE()) 在以前的版本中,你将不得不使用例如CAST(CONVERT(VARCHAR(10), STAMP, 112) as Date)

所以完整的SQL看起来像:

Select CAST(CONVERT(VARCHAR(10), STAMP, 112) as Date) as [Date]
,COUNT(*) as [Passed First Time]
from tbl_results
join
(
Select UID 
from tbl_results
Where TestName='Finished'
Group by UID
Having Count(*)=1
) x on x.UID=tbl_results.UID
Where TestName='Finished' and Pass='P' and Stamp > '2013-11-01'
Group by  CAST(CONVERT(VARCHAR(10), STAMP, 112) as Date)
ORDER BY CAST(CONVERT(VARCHAR(10), STAMP, 112) as Date)

答案 1 :(得分:0)

最后排序了!现在就像一个魅力。感谢bummi和Kiril的建议。

如果将来有人需要这个 - 一旦我掌握了一些东西,我还添加了一些额外的功能。

SELECT u.UID
      ,TestRig
      ,CONVERT (Date, [Stamp]) AS Date
      ,Description
FROM (
     SELECT UID
           ,COUNT (UID) AS Attempts
     FROM [dbase].[dbo].[tbl_results]
     where TestRig IN ('RigOne', 'RigTwo')
       and TestName = 'Finished'
       and Stamp > '2013-12-01'
     GROUP BY UID) AS u 

JOIN (
     SELECT UID
           ,Pass
           ,TestName
           ,Stamp
           ,TestRig
           ,Description
     FROM [dbase].[dbo].[tbl_results]
     ) AS r
ON (u.UID = r.UID)
where u.Attempts = 1
  and r.Pass = 'P'
  and TestRig IN ('RigOne', 'RigTwo')
  and TestName = 'Finished'
  and Stamp > '2013-12-01'
  and Pass = 'P'