See this fiddle. I have a table with questions where each question falls into a category and I have to find user averages of each category. I think it is working fine but I wanted to add a total that shows the total number of answers being included in the average for each user. I can not figure out what to put in my where clause to actually return the total number of questions for each user. Whether I include userid,QID,or choice it is giving me astronomical numbers.
Query SQL:
DECLARE @tblTmpCatStats TABLE (userid NVARCHAR(10),cat1_mean FLOAT,cat2_mean FLOAT,cat3_mean FLOAT,cat4_mean FLOAT,N FLOAT)
INSERT INTO @tblTmpCatStats SELECT d.userid
,AVG(CAST(c1.choice AS FLOAT))
,AVG(CAST(c2.choice AS FLOAT))
,AVG(CAST(c3.choice AS FLOAT))
,AVG(CAST(c4.choice AS FLOAT))
,COUNT(d.userid)
FROM tblTmpDemographics d
JOIN tblTmpDemographics c1 ON d.userid = c1.userid
JOIN tblTmpDemographics c2 ON d.userid = c2.userid
JOIN tblTmpDemographics c3 ON d.userid = c3.userid
JOIN tblTmpDemographics c4 ON d.userid = c4.userid
WHERE c1.QID IN ('1','5')
AND c2.QID IN ('2','6')
AND c3.QID IN ('3','7')
AND c4.QID IN ('4','8')
GROUP BY d.userid
SELECT * FROM @tblTmpCatStats
I am trying to make N eqaul to the total number choices included in the AVG
Setup SQL:
CREATE TABLE tblTmpDemographics (userid NVARCHAR(10),QID INT,choice NVARCHAR(1000))
INSERT INTO tblTmpDemographics (userid,QID,choice)
SELECT 'user1',1,'5' UNION ALL SELECT 'user1',2,'3' UNION ALL
SELECT 'user1',3,'4' UNION ALL SELECT 'user1',4,'5' UNION ALL
SELECT 'user1',5,'5' UNION ALL SELECT 'user1',6,'3' UNION ALL
SELECT 'user1',7,'4' UNION ALL SELECT 'user1',8,'5' UNION ALL
SELECT 'user2',1,'3' UNION ALL SELECT 'user2',2,'2' UNION ALL
SELECT 'user2',3,'3' UNION ALL SELECT 'user2',4,'5' UNION ALL
SELECT 'user2',5,'3' UNION ALL SELECT 'user2',6,'2' UNION ALL
SELECT 'user2',7,'3' UNION ALL SELECT 'user2',8,'5' UNION ALL
SELECT 'user3',1,'2' UNION ALL SELECT 'user3',2,'1' UNION ALL
SELECT 'user3',3,'5' UNION ALL SELECT 'user3',4,'5' UNION ALL
SELECT 'user3',5,'2' UNION ALL SELECT 'user3',6,'1' UNION ALL
SELECT 'user3',7,'5' UNION ALL SELECT 'user3',8,'5' UNION ALL
SELECT 'user4',1,'4' UNION ALL SELECT 'user4',2,'3' UNION ALL
SELECT 'user4',3,'3' UNION ALL SELECT 'user4',4,'5' UNION ALL
SELECT 'user4',5,'4' UNION ALL SELECT 'user4',6,'3' UNION ALL
SELECT 'user4',7,'3' UNION ALL SELECT 'user4',8,'5' GO
Why is it returning 128 and not 8?
Try this:
See SQL Fiddle with Demo