0

我正在尝试对一组值进行计数,但计数会带来额外的值。

这是一些背景信息。以下 T-SQL 查询返回我需要的数据:

SELECT DISTINCT [REQ_INFO].UDAValue as 'UDA value', REQ_INFO.ProjectID, 
REQ_INFO.BaselineID, Req_ID
FROM [REQ_INFO]
INNER JOIN [Project_INFO] ON [REQ_INFO].[ProjectID]=[Project_INFO].[ProjectID]
INNER JOIN [Baseline_INFO]ON [REQ_INFO].[BaselineID]=[Baseline_INFO].[BaselineID]
WHERE [Project_INFO].[Name] = 'Address Book'
AND [Baseline_INFO].Name = 'Current Baseline'
AND [UDAName] = 'Requirement Priority'
ORDER BY REQ_INFO.Req_ID

这将返回以下数据:

在此处输入图像描述

我还需要计算每个值在 UDA 值列中出现的次数。如上所示,总和应为 11。但是我尝试了以下代码,但它正在计算额外的行:

SELECT [REQ_INFO].UDAValue as 'UDA value',COUNT (*) as 'UDA Num'
FROM [REQ_INFO]
INNER JOIN [Project_INFO] ON [REQ_INFO].[ProjectID]=[Project_INFO].[ProjectID] 
INNER JOIN [Baseline_INFO]ON [REQ_INFO].[BaselineID]=[Baseline_INFO].[BaselineID]
WHERE [Project_INFO].[Name] = 'Address Book' 
AND [Baseline_INFO].Name = 'Current Baseline'
AND [UDAName] = 'Requirement Priority'
GROUP BY REQ_INFO.UDAValue

在此处输入图像描述

有人对我做错了什么有建议吗?

4

3 回答 3

2

更改您的计数以包括不同的;像这样的东西:

SELECT [REQ_INFO].UDAValue as 'UDA value',COUNT (DISTINCT REQ_INFO.Req_ID) as 'UDA Num'
... rest of your query
于 2012-06-13T16:27:54.027 回答
2

在我看来,这很可能是distinct第一个查询中的语句导致了差异。

如果您要查找的是 [REQ_INFO].UDAValue 出现的实际计数。然后,您应该distinct从第一个查询中删除该子句,以查看第二个查询实际计数的内容。

作为替代方案,您可以像这样查看第一个查询的分组值的总数,但这与您的第一个和第二个查询不同。

SELECT [REQ_INFO].UDAValue as 'UDA value',COUNT (*) as 'UDA Num' 
FROM [REQ_INFO] 
INNER JOIN [Project_INFO] ON [REQ_INFO].[ProjectID]=[Project_INFO].[ProjectID]  
INNER JOIN [Baseline_INFO]ON [REQ_INFO].[BaselineID]=[Baseline_INFO].[BaselineID] 
WHERE [Project_INFO].[Name] = 'Address Book'  
AND [Baseline_INFO].Name = 'Current Baseline' 
AND [UDAName] = 'Requirement Priority' 
GROUP BY REQ_INFO.UDAValue, REQ_INFO.ProjectID, REQ_INFO.BaselineID, Req_ID

从你的问题中很难判断这是否是你想要的。如果您真的想要对第一个查询中出现的值进行计数(影响 4 列和所有列的不同语句)。然后你可能会用子查询来处理它。

于 2012-06-13T16:25:08.997 回答
0

我能够通过创建一个临时表让我执行计数来解决这个问题。这是我使用的 SQL 语句:

DECLARE @UDAcount TABLE (UDAValue nvarchar(max), ProjectID int, 
BaselineID int, Req_ID int, Version nvarchar(128))

INSERT INTO @UDAcount (UDAValue, ProjectID, BaselineID, Req_ID, Version)
SELECT DISTINCT [REQ_INFO].UDAValue as 'UDA value', REQ_INFO.ProjectID, 
REQ_INFO.BaselineID, Req_ID, REQ_INFO.Version
FROM [REQ_INFO]
INNER JOIN [Project_INFO] ON [REQ_INFO].[ProjectID]=[Project_INFO].[ProjectID]
INNER JOIN [Baseline_INFO]ON [REQ_INFO].[BaselineID]=[Baseline_INFO].[BaselineID]
WHERE [Project_INFO].[Name] = 'Address Book'
AND [Baseline_INFO].Name = 'Current Baseline'
AND [UDAName] = 'Requirement Priority'
ORDER BY REQ_INFO.Req_ID

SELECT UDAValue as 'UDA value',COUNT (*) as 'UDA Num'
FROM @UDAcount
GROUP BY UDAValue

它可能不是最优雅的解决方案,但它确实返回了所需的结果。如果您对如何改进这一点有任何建议,我很高兴听到他们的声音。

于 2012-06-14T11:00:27.967 回答