2012-03-12 150 views
0

我有一张表格,它给出了使用计数函数进行考试的分数。我需要执行相同的功能来比较test1和test2。sql比较两个表格

找到第一次考试成绩我使用计数功能和执行增加一些约束在where子句中,以及后来的用户名分组,

我需要这将需要第二计数比较这计数在第二个select语句中,但是我无法在having子句中添加select语句,并且我无法对where子句中的count进行任何操作。下面是我现在所拥有的一个基本想法

SELECT ur.uno, COUNT(*)*5 as test1 
FROM question q, 
     userresponse ur 
WHERE q.eno = '1' 
    AND q.eno = ur.eno 
    AND q.qno = ur.qno 
    AND q.correctanswer = ur.response 
    AND test1 > (SELECT ur.uno, COUNT(*)*5 
       FROM question q1, 
         userresponse ur1 
       WHERE q1.eno = '3' 
        AND q1.eno = ur1.eno 
        AND q1.qno = ur1.qno 
        AND q1.correctanswer = ur1.response 
      GROUP BY ur.no) 
GROUP BY ur.uno 

这是我的第一种方法,但是我得到一个test1无效的标识符。我的另一种方法是

select ur.uno, count(*)*5 as test1 
from question q, userresponse ur 
where q.eno = '1' and q.eno = ur.eno and q.qno = ur.qno and q.correctanswer = ur.response 
group by ur.uno 
having count(*)*5 > (select ur1.uno, count(*)*5 as test3 
from question q1, userresponse ur1 
where q1.eno = '3' and q1.eno = ur1.eno and q1.qno = ur.qno and q.correctanswer = ur.response 
group by ur1.uno) 

但我得到了太多的值错误,任何想法?

回答

1

尝试:

SELECT ur.uno, 
     COUNT(case when q.eno='1' then 1 end)*5 as test1, 
     COUNT(case when q.eno='3' then 1 end)*5 as test3 
FROM question q, 
     userresponse ur 
WHERE q.eno in ('1', '3') 
    AND q.eno = ur.eno 
    AND q.qno = ur.qno 
    AND q.correctanswer = ur.response 
HAVING COUNT(case when q.eno='1' then 1 end) > 
     COUNT(case when q.eno='3' then 1 end) 
0

在第一查询

where子句不承认的别名,所以你可以替换test1的。

在第二个查询

你可以改变

select ur1.uno, count(*)*5 as test3 

select count(*)*5 as test3 

在第二个SELECT语句,以避免过多的数值错误。

1

@ user541597; 嘿从内部查询,我认为它会工作除去 “ur.uno” ..