我正在尝试对一组值进行计数,但计数会带来额外的值。
以下是一些背景信息。以下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
有没有人对我做错了什么有建议?
答案 0 :(得分: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列和所有列的不同语句)。然后你可能会用子查询来接近它。
答案 1 :(得分:2)
更改您的计数以包含明显的;像这样的东西:
SELECT [REQ_INFO].UDAValue as 'UDA value',COUNT (DISTINCT REQ_INFO.Req_ID) as 'UDA Num'
... rest of your query
答案 2 :(得分: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
它可能不是最优雅的解决方案,但它确实会返回所需的结果。如果您对如何改进这方面有任何建议,我很高兴听到它们。