Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
911 views
in Technique[技术] by (71.8m points)

sql server - SQL - Returning all rows even if count is zero for item

I am performing a count based on a date range. Currently the query does return the correct result but I require additional information. In it's current form, the query shows the item with the correct count. However I need all items to be shown, even if their count is zero for the date range specified.

Here is the SQL code:

INSERT INTO @CreationCount (BaselineID, Name)

SELECT distinct [BaselineID],[Name] 
FROM [Baseline_INFO] 

DECLARE @ReqType TABLE (Type nvarchar(128))
INSERT INTO @ReqType (Type)
SELECT DISTINCT Tree.Type as 'Requirement Type'
FROM [TREE]
INNER JOIN [Project_INFO]  ON [Project_INFO].[ProjectID]=[Tree].[Project_ID] 
INNER JOIN [Baseline_INFO] ON [Baseline_INFO].[BaselineID]=[Tree].[Baseline_ID]
WHERE [Project_INFO].[Name] = 'Address Book' AND [Baseline_INFO].[Name] = 'Current
Baseline' 
Group By Tree.Type

SELECT Tree.Type as 'Requirement Type', COUNT(Tree.Type) as 'Number in Creation Range' 
FROM [Tree] 
INNER JOIN @ReqType As RT on RT.Type = Tree.Type
INNER JOIN [Project_INFO]  ON [Project_INFO].[ProjectID]=[Tree].[Project_ID] 
INNER JOIN @CreationCount AS CCount ON CCount.BaselineID=Tree.Baseline_ID 
WHERE [Project_INFO].[Name] = 'Address Book' AND CCount.Name = 'Current Baseline' 
AND [Tree].[creationDate] >= ('2010-01-01') and [Tree].[creationDate] < ('2020-01-01') 
GROUP BY tree.Type

When I execute this query I get the following result:

https://dl.dropbox.com/u/17234826/SQLresult.png

This result is correct however I need all requirement types to be list, even if there are no requirements in the creation range, i.e.

https://dl.dropbox.com/u/17234826/SQLresult1.png

I have tried using various joins, IFNULL and ISNULL but I haven't got anything to work.

If someone could point me in the right direction I'd appreciate it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Modify the second query

SELECT Tree.Type as 'Requirement Type',
       COUNT(CASE WHEN [Tree].[creationDate] >= ('2010-01-01') and [Tree].[creationDate] < ('2020-01-01') THEN Tree.Type END) AS 'Number in Creation Range'
FROM [Tree] 
INNER JOIN @ReqType As RT on RT.Type = Tree.Type
INNER JOIN [Project_INFO]  ON [Project_INFO].[ProjectID]=[Tree].[Project_ID] 
INNER JOIN @CreationCount AS CCount ON CCount.BaselineID=Tree.Baseline_ID 
WHERE [Project_INFO].[Name] = 'Address Book' AND CCount.Name = 'Current Baseline' 
GROUP BY tree.Type

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...