看到这个小提琴。我有一个问题表,其中每个问题都属于一个类别,我必须找到每个类别的用户平均值。我认为它工作正常,但我想添加一个总数,显示每个用户的平均值中包含的答案总数。我不知道要在 where 子句中放入什么来实际返回每个用户的问题总数。无论我包含用户 ID、QID 还是选项,它都给了我天文数字。
查询 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
我正在尝试使 N 等于 AVG 中包含的选择总数
设置 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
为什么它返回 128 而不是 8?