SQL QUERY中的条件WHERE

时间:2014-09-15 21:27:05

标签: sql

我有这个数据库:

enter image description here

我在R中使用SQL代码,但本文的重点是如何在SQL中进行查询。

我提出了这个问题:

> se<- sqldf("select ALUMNO , ESTADO as FIRSTANSWERALG, NIVEL from stbase where CURSO='Algebra' AND NPREGUNTA='pregunta 1' AND NIVEL='BASICO 1' ")
> head(se)
                          ALUMNO FIRSTANSWERALG    NIVEL
1      ABANTO PICHIGUA JOSE LUIS       Correcta BASICO 1
2     AGUILAR GUTIERREZ KIMBERLY     Incorrecta BASICO 1
3   ARANGO MENDIETA FREDY JULIAN       Correcta BASICO 1
4     ARIAS OROSCO SHEYLA ANDREA       Correcta BASICO 1
5 AYALA CORNEJO KARLA FRANSHESKA       Correcta BASICO 1
6          CARDENAS SONCCO HEIDY       Correcta BASICO 1

此查询选择主题“代数”中第一个问题(PREGUNTA 1)的答案。但是,我想查询选择其他问题和其他科目的答案。例如:

                       ALUMNO    FIRSTANSWERALG    THIRDANSWERARI              NIVEL
1      ABANTO PICHIGUA JOSE LUIS       Correcta     Correcta                  BASICO 1
2     AGUILAR GUTIERREZ KIMBERLY     Incorrecta     Correcta                  BASICO 1
3   ARANGO MENDIETA FREDY JULIAN       Correcta     En blanco                 BASICO 1
4     ARIAS OROSCO SHEYLA ANDREA       Correcta     Incorrecta                BASICO 1
5 AYALA CORNEJO KARLA FRANSHESKA       Correcta     Correcta                  BASICO 1
6          CARDENAS SONCCO HEIDY       Correcta     Correcta                  BASICO 1

在此数据库中,添加了主题“算术”中的第三个答案。那么如何添加某个主题的答案列。

编辑:CURSO的值集是:'Aritmetica','代数','Geometria'。英语中的CURSO意味着主题。 THIRDANSWEARI意为'Aritmetica'主题中'Pregunta 3'的答案。

2 个答案:

答案 0 :(得分:0)

我认为这可以得到你想要的并不是很难。我相信下面的查询输出是你要找的。让我知道它是否有效。谢谢!

select 
ALUMNO, 
ESTADO as FIRSTANSWERALG, 
NIVEL,
NPREGUNTA as THIRDANSWERARI

from stbase 

-- (remove this if 2 lines below get removed) --
where 
-- (remove this if you want to show more questions) --
CURSO='Aritmetica' 
-- (remove this if you don't want to limit your output to 'BASICO 1' in your NiVEL column) --
AND NIVEL='BASICO 1'

我想了解你的问题。到目前为止,我知道您正在尝试向名为THIRDANSWERARI的查询输出添加一列。我的问题是THIRDANSWERARI列中的数据是否在您选择的数据库中,或者您想手动放入?

答案 1 :(得分:0)

我相信这段时间会有用,因为我明白你现在在说什么:D

select
t1.ALUMNO,
t1.FIRSTANSWERALG,
t2.THIRDANSWERALG,
t1.NIVEL

FROM
(select 
ALUMNO, 
ESTADO as FIRSTANSWERALG, 
NIVEL

from stbase 

where 
CURSO='Aritmetica' 
AND NPREGUNTA='pregunta 1'
AND NIVEL='BASICO 1') t1

JOIN
(select 
ALUMNO, 
ESTADO as THIRDANSWERALG, 
NIVEL

from stbase 

where 
CURSO='Aritmetica' 
AND NPREGUNTA='pregunta 3'
AND NIVEL='BASICO 1') t2 ON t1.ALUMNO = t2.ALUMNO

请注意:您可以在此查询中更改CURSO值以获取其他主题的答案。例如:CURSO =&#39;代数&#39;在上面的两个WHERE语句中获得&#39;代数&#39;的答案而不是Aritmetica&#39;