Click here to Skip to main content
15,917,328 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Dear all,

I have this stored procedure which returns aggregated data, and I have faced a problem, it has been a while since I worked on sql scripts, I wanted to count a column that has more than one frequency, however, the script's output is not as I wanted.

The sample script is as follows:

NOTE: for convenience, I have changed the real names of the tables...

Please feel free if you guys have any question or explanation.

Thanks in Advance

What I have tried:

SQL
BEGIN

DECLARE @AppSettings TABLE(Name NVARCHAR(50) NULL)	
	
	INSERT INTO @AppSettings 
	SELECT SettingName FROM ApplicationSetting 

DECLARE @Users TABLE(Name NVARCHAR(50) NULL)

	INSERT INTO @Users 	
	SELECT UserName FROM UserProfile  

DECLARE @Activities TABLE(Name NVARCHAR(50) NULL)

	INSERT INTO @Activities 
	SELECT Name FROM StateTemplate 


SELECT  Table2.Name AS ActivityName, --		
		Count(Table2.Name) AS ActivityCount, -- Frequency 
		Table1.PerformedBy, -- 
		Table4.SettingName

FROM        Table1 INNER JOIN 
			Table5 ON Table1.ParentBusinessProcessID = Table5.BusinessProcessID INNER JOIN 
			Table3 ON Table5.ProcessTypeID = Table3.ProcessTemplateID INNER JOIN
            Table2 ON Table3.ProcessTemplateID = Table2.ParentProcessTemplateID INNER JOIN
            Table4 ON Table3.ProcessTemplateID = Table4.SettingValue

WHERE			Table4.SettingName IN (SELECT * FROM @AppSettings) AND
				Table1.PerformedBy IN (SELECT * FROM @Users) --AND
				Table2.Name In (SELECT * FROM @Activities)

GROUP BY		Table2.Name, 
				Table1.PerformedBy,
				Table4.SettingName

ORDER BY		PerformedBy

END
Wrong OUTPUT 

ZZ	8	userNameX 	AA
ZZ	4	userNameX 	BB
YY      8	userNameX 	AA
YY      4	userNameX 	BB
XX	8	userNameX 	AA
XX	4	userNameX 	BB
WW	8	userNameX 	AA
WW	4	userNameX 	BB
VV	8	userNameX 	AA
VV	4	userNameX 	BB
Posted
Updated 8-Dec-16 19:51pm
v3
Comments
CHill60 8-Dec-16 13:45pm    
Sample data would help
jamuro77 9-Dec-16 1:46am    
It would be necessary to know more about, at least two issues:
1) Which is the correct result set you are looking for?
2) Further information about data in tables
Yonathan1111 9-Dec-16 3:14am    
okay, I will post what the correct data could look like later on.

1 solution

As I said in previous comments it would be necessary yo know more about this question. Anyway you should know the following. Perhaps it is useful for you:

1) Count([FieldName]) only counts not null values in FieldName
2) Count(distinct [FieldName]) only counts unique not null values in FieldName
3) Count (*) counts all values, including null, in FieldName
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900