Adding a new row to empty dataframe located in data lake - apache-spark-sql

I created a empty dataframe table to location at Delta by using this code below:
deltaResultPath = "/ml/streaming-analysis/delta/Result"
# Create Delta Lake table
sqlq = "CREATE TABLE stockDailyPrices_delta USING DELTA LOCATION '" + deltaResultPath + "'"
spark.sql(sqlq)
I am new to spark and do not fully understand sparkSQL code. What I want to do is instead of inserting values from another dataframe, I would like to add values generated in python script.
Something like modifying the code from:
insert_sql = "insert into stockDailyPrices_delta select f.* from stockDailyPrices f where f.price_date >= '" + price_date_min.strftime('%Y-%m-%d') + "' and f.price_date <= '" + price_date_max.strftime('%Y-%m-%d') + "'"
spark.sql(insert_sql)
to
Time = 10
cpu_temp = 3
dsp_temp = 5
insert_sql = "insert into df (Time, cpu_temp, dsp_temp) values (%s, %s, %s)"
spark.sql(insert_sql)
However, I see the error following:
org.apache.spark.sql.catalyst.parser.ParseException:
ParseException: "\nmismatched input 'Time' expecting {'(', 'SELECT', 'FROM', 'DESC', 'VALUES', 'TABLE', 'INSERT', 'DESCRIBE', 'MAP', 'MERGE', 'UPDATE', 'REDUCE'}(line 1, pos 16)\n\n== SQL ==\ninsert into df (Time, cpu_temp, dsp_temp) values (%s, %s, %s)\n----------------^^^\n"
How can I fix this code?

I could make it work with something like this
spark.sql("insert into Result_delta select {} as Time, {} as cpu_temp, {} as dsp_temp".format(Time, cpu_temp, dsp_temp))

Related

dateRangeInput in reactive SQl query- date output is in wrong format

Has anyone faced the problem with dateRangeInput? I want to use it to filter my data, however the output of the dateRangeInput is wrong as 2016-02-21, and I need it to be 21.02.2016. I thought that the format=dd.mm.yyyy will solve it, however I do not get any change..
My code:
library(ROracle)
library(shiny)
library(DT)
server <- shinyServer(
function(input, output, session) {
con <- dbConnect(dbDriver("Oracle"),"xx/K",username="user",password="pwd")
tableList <- dbListTables(con,schema="K")
updateSelectizeInput(session, "tabnames", server = TRUE, choices = tableList)
output$date_ui=renderUI({
dateRangeInput('date',
label = 'Datum: dd.mm.yyyy',
start = Sys.Date()-1, end = Sys.Date()+1,
separator = " bis ",
format = 'dd.mm.yyyy',language = "de")
})
sqlOutput <- reactive({
sqlInput <- paste("select rownum * from K.",input$tabnames, "where dati_create between to_date('",format(input$date[1]),"','dd.mm.yyyy') and to_date('",input$date[2],"','dd.mm.yyyy')")
print(sqlInput) # I have printed it to see the format of the date
dbGetQuery(con$cc, sqlInput, stringsAsFactors = T)
})
output$table <- DT::renderDataTable(sqlOutput(), server=TRUE, rownames=TRUE, filter="top", options=list(pageLength=10))
session$onSessionEnded(function() { dbDisconnect(con) })
})
ui_panel <-
tabPanel("Test",
sidebarLayout(
sidebarPanel(
),
mainPanel(
selectizeInput("tabnames",label = "server side", choices = NULL),
uiOutput("date_ui"),
tableOutput("out"),
tableOutput("table")
)
)
)
ui <- shinyUI(navbarPage("Test",ui_panel))
runApp(list(ui=ui,server=server))
After printing sqlInput:
[1] "select rownum * from K.xy where dati_create between to_date(' 2016-02-21 ','dd.mm.yyyy') and to_date(' 2016-02-23 ','dd.mm.yyyy')"
Error in .oci.GetQuery(conn, statement, data = data, prefetch = prefetch, :
ORA-01861: literal does not match format string
Does anyone have an idea how I can change the format of the date in dateRangeInput?
Thanks for any help!

python- how to join two seperate queries based on common value

I have two queries which links to different databases
query = "select name ,ctry from xxxx where xxxx"
cursor.execute(query)
results1 = list(cursor.fetchall())
for row in results1:
query1 = "SELECT sessionname, country FROM xxx where and sessions.sessionname = '"+row[0] +"'"
cur.execute(query1)
results2.append(cur.fetchall())
How to connect them if they have common value(sessionname and name) and save it's output to file. Both queries are located in different dbo (oracle, postgresql)
My code is here :
try:
query = """select smat.s_name "SQLITE name" ,smed.m_ctry as "Country", smed.m_name "HDD Label" from smart.smed2smat ss, smart.smed smed, smart.smat smat where ss.M2S_SMAT=smat.s_id and ss.m2s_smed=smed.m_id and smed.m_name like '{0}%' order by smat.s_name""" .format(line_name)
cursor.execute(query)
columns = [i[0] for i in cursor.description]
results1 = cursor.fetchall()
for row in results1:
query1 = "SELECT sessions.sessionname, projects.country , projects.projectname FROM momatracks.sessions, momatracks.projects, momatracks.sessionsgeo where sessions.projectid = projects.id and sessionsgeo.sessionname = sessions.sessionname and sessions.sessionname = '"+row[0] +"' order by sessions.sessionname"
cur.execute(query1)
results2 =cur.fetchall()
print "results1 -----> \n:", row
tmp=[]
output_items = []
for tmp in results2:
print "---> \n", tmp
try:
stations_dict = dict([(item[0], item[1:]) for item in tmp])
for item in row:
output_item = list(item) + stations_dict.get(item[0], [])
output_items.append(output_item)
except Exception, f:
print str (f)
cursor.close()
cur.close()
except Exception, g:
print str ( g )
except Exception, e:
print str ( e )
My results from row and tmp are :
row - WE246JP_2015_10_11__14_53_33', 'NLD', '031_025_SQLITE_NLD1510_03INDIA
and
tmp - WE246JP_2015_10_11__14_53_33', 'NLD', 'NLD15_N2C1-4_NL'
How to properly connect them? I want output look like this :
output_items - WE246JP_2015_10_11__14_53_33', 'NLD', '031_025_SQLITE_NLD1510_03INDIA', 'NLD15_N2C1-4_NL'
At the moment i get this error :
can only concatenate list (not "str") to list
Also value station_dict looks like this :( And this is not what i intended to do
'W': 'E246JP_2015_10_11__15_23_33', 'N': 'LD15_N2C1-4_NL3'
I know there is something wrong with my code which is simmilar to join. Can anyone explain this to me ? I used method below :
http://forums.devshed.com/python-programming-11/join-arrays-based-common-value-sql-left-join-943177.html
If the sessions are exactly the same in both databases then just zip the results:
query = """
select
smat.s_name "SQLITE name",
smed.m_ctry as "Country",
smed.m_name "HDD Label"
from
smart.smed2smat ss
inner join
smart.smed smed on ss.M2S_SMAT = smat.s_id
inner join
smart.smat smat on ss.m2s_smed = smed.m_id
where smed.m_name like '{0}%'
order by smat.s_name
""".format(line_name)
cursor.execute(query)
results1 = cursor.fetchall()
query1 = """
select
sessions.sessionname,
projects.country,
projects.projectname
from
momatracks.sessions,
inner join
momatracks.projects on sessions.projectid = projects.id
inner join
momatracks.sessionsgeo on sessionsgeo.sessionname = sessions.sessionname
where sessions.sessionname in {}
order by sessions.sessionname
""".format(tuple([row[0] for row in results1]))
cur.execute(query1)
results2 = cur.fetchall()
zipped = zip(results1, results2)
output_list = [(m[0][0], m[0][1], m[0][2], m[1][2]) for m in zipped]
If the sessions are different then make each result a dictionary to join.
I think you can use a subquery here. There's no way for me to test it, but I think it should look like this:
SELECT *
FROM (SELECT smat.s_name "SQLITE name" ,
smed.m_ctry as "Country",
smed.m_name "HDD Label"
FROM smart.smed2smat ss,
smart.smed smed,
smart.smat smat
WHERE ss.M2S_SMAT=smat.s_id
AND ss.m2s_smed=smed.m_id
AND smed.m_name like '{0}%'
ORDER BY smat.s_name) t1,
(SELECT sessions.sessionname,
projects.country ,
projects.projectname
FROM momatracks.sessions,
momatracks.projects,
momatracks.sessionsgeo
WHERE sessions.projectid = projects.id
AND sessionsgeo.sessionname = sessions.sessionname
AND sessions.sessionname = '"+row[0] +"'
ORDER BY sessions.sessionname) t2
WHERE t1."SQLITE name" = t2.sessionname ;

Confused about behavior of setResultsName in Pyparsing

I am trying to parse a few SQL statements. Here is a sample:
select
ms.member_sk a,
dd.date_sk b,
st.subscription_type,
(SELECT foo FROM zoo) e
from dim_member_subscription_all p,
dim_subs_type
where a in (select moo from t10)
I am interested in getting tables only at this time. So I would like to see
[zoo, dim_member_subscription_all, dim_subs_type] & [t10]
I have put together a small script looking at Paul McGuire's example
#!/usr/bin/env python
import sys
import pprint
from pyparsing import *
pp = pprint.PrettyPrinter(indent=4)
semicolon = Combine(Literal(';') + lineEnd)
comma = Literal(',')
lparen = Literal('(')
rparen = Literal(')')
update_kw, volatile_kw, create_kw, table_kw, as_kw, from_kw, \
where_kw, join_kw, left_kw, right_kw, cross_kw, outer_kw, \
on_kw , insert_kw , into_kw= \
map(lambda x: Keyword(x, caseless=True), \
['UPDATE', 'VOLATILE', 'CREATE', 'TABLE', 'AS', 'FROM',
'WHERE', 'JOIN' , 'LEFT', 'RIGHT' , \
'CROSS', 'OUTER', 'ON', 'INSERT', 'INTO'])
select_kw = Keyword('SELECT', caseless=True) | Keyword('SEL' , caseless=True)
reserved_words = (update_kw | volatile_kw | create_kw | table_kw | as_kw |
select_kw | from_kw | where_kw | join_kw |
left_kw | right_kw | cross_kw | on_kw | insert_kw |
into_kw)
ident = ~reserved_words + Word(alphas, alphanums + '_')
table = Combine(Optional(ident + Literal('.')) + ident)
column = Combine(Optional(ident + Literal('.')) + (ident | Literal('*')))
column_alias = Optional(Optional(as_kw).suppress() + ident)
table_alias = Optional(Optional(as_kw).suppress() + ident).suppress()
select_stmt = Forward()
nested_table = lparen.suppress() + select_stmt + rparen.suppress() + table_alias
table_list = delimitedList((nested_table | table) + table_alias)
column_list = delimitedList((nested_table | column) + column_alias)
txt = """
select
ms.member_sk a,
dd.date_sk b,
st.subscription_type,
(SELECT foo FROM zoo) e
from dim_member_subscription_all p,
dim_subs_type
where a in (select moo from t10)
"""
select_stmt << select_kw.suppress() + column_list + from_kw.suppress() + \
table_list.setResultsName('tables', listAllMatches=True)
print txt
for token in select_stmt.searchString(txt):
pp.pprint(token.asDict())
I am getting the following nested output. Can anybody please help me understand what I am doing wrong?
{ 'tables': ([(['zoo'], {}), (['dim_member_subscription_all', 'dim_subs_type'], {})], {})}
{ 'tables': ([(['t10'], {})], {})}
searchString will return a list of all matching ParseResults - you can see the tables value of each using:
for token in select_stmt.searchString(txt):
print token.tables
Giving:
[['zoo'], ['dim_member_subscription_all', 'dim_subs_type']]
[['t10']]
So searchString found two SELECT statements.
Recent versions of pyparsing support summing this list into a single consolidated using Python builtin sum. Accessing the tables value of this consolidated result looks like this:
print sum(select_stmt.searchString(txt)).tables
[['zoo'], ['dim_member_subscription_all', 'dim_subs_type'], ['t10']]
I think the parser is doing all you want, you just need to figure out how to process the returned results.
For further debugging, you should start using the dump method on ParseResults to see what you are getting, which will print the nested list of returned tokens, and then a hierarchical tree of all named results. For your example:
for token in select_stmt.searchString(txt):
print token.dump()
print
prints:
['ms.member_sk', 'a', 'dd.date_sk', 'b', 'st.subscription_type', 'foo', 'zoo', 'dim_member_subscription_all', 'dim_subs_type']
- tables: [['zoo'], ['dim_member_subscription_all', 'dim_subs_type']]
['moo', 't10']
- tables: [['t10']]

sql statement how to keep null value

This query here is executed on 3 tables(students) one which makes a zero on the exam so his q.correctanswer != ur.response, how can I keep the 0 value in my output. When i execute this statement it only gives me two values instead of 3 for each student.
select count(*) as Test1
from users u, question q, userresponse ur
where q.eno = '1'
and q.eno = ur.eno
and q.qno = ur.qno
and ur.response = q.correctanswer
and u.uno = ur.uno
group by u.uno
sample data:
Note:
- "||" is used to concatenate strings
- each string is between a pair of single quotes.
- each record is between "(" and ")".
- fields are ordered according to fields in tables
- "\n" means a new line
======exams data==========
(1,'Java Programming',60,1)
(3,'Elementary History',10,3)
======questions data===========
(1,1,'Choose the operations that can be performed on String
objects:(A) +\n(B) + =\n(C) -\n(D) %\n(E) ^','B')
(1,2,'What will be the result of the expression\na % b\nwhen a and b
are of type int and their values are a = -17 and b = -6?','A')
(1,3,'What will be the result of the expression\na % b\nwhen a and b
are of type int and their values are a = 10 and b = 6?','B')
(1,4,'Consider the following code:\nint x, y, z\ny = 1\nz = 5\nx = 0
- (++y) + z++\nAfter execution of this, what will be the values of x, y and z?','C')
(1,5,'Identify the statements that are correct:\n(A) int a = 13,
a>>2 = 3\n(B) int b = -8, b>>1 = -4\n(C) int a = 13, a>>>2 = 3\n(D)
int b = -8, b>>>1 = -4','E')
(1,6,'If not assigned a value, a variable of type char has the
following default value:','A')
(1,7,'What will be the value of a after execution of the following
statements:\nint a = 23, b = 34\na = ((a < b) ? (b + a) : (b -
a)','B')
(1,8,'Which of the following is not a hexadecimal number?\n(A)
999\n(B) (hex)23\n(C) 0x556\n(D) 0x1F2','C')
(1,9,'if(check4Biz(storeNum) != null) {}\nReferring to the above,
what datatype could be returned by method check4Biz()?','D')
(1,10,'Select the invalid assignment statements from the
following:\n(A) float x = 238.88\n(B) double y = 0x443\n(C) int n =
(int) true\n(D) long m =778645','A')
(1,11,'int j\nfor(int i=0i<14i++) {\nif(i<10) {\nj = 2 +
i\n}\nSystem.out.println("j: " + j + " i: " + i)\n}\nWhat is WRONG
with the above code?','E')
(1,12,'Consider the following code:\nclass ClassA\n{\npublic static
void main(String args [ ])\n{\nClassB b = classB()\n}\nClassA(int x) {
}\n}\nclass ClassB extends ClassA\n{\n}\nWhat will happen when we
compile and run this code?','A')
(1,13,'The keywords reserved but not used in the initial version of
Java are:\n(A) union\n(B) const\n(C) inner\n(D) goto\n(E) boolean\n(F)
synchronized','C')
(1,14,'We would like to make a member of a class visible in all
subclasses regardless of what package they are in. Which one of the
following keywords would achieve this?','D')
(1,15,'Which of the following are not keywords?\n(A) NULL\n(B)
implements\n(C) protected\n(D) extended\n(E) string','B')
(3,1,'The Battle of Gettysburg was fought during which war?','C')
(3,2,'Neil Armstrong and Buzz Aldrin walked how many \n' ||
'minutes on the moon in 1696?','B')
(3,3,'Which Presidents held office during World War II?','D')
(3,4,'In a communist economic system, people:','B')
(3,5,'Which president did not die while in office?','D')
(3,6,'Which state refused to attend the Constitutional Convention
\n' ||
'in 1787 because it didn''t want the United States government \n' ||
'to interfere with already established state affairs?','A')
(3,7,'Who founded Buddhism?','A')
(3,8,'Where is India?','D')
(3,9,'What is the dominant religion in India?','B')
(3,10,'Near which river did archaeologists find India''s \n' ||
'first civilization?','B')
========== answerOption data ============
(3,8,'A','Australia') (3,8,'B','America') (3,8,'C','Africa')
(3,8,'D','Asia') (3,1,'A','World War II') (3,1,'B','The
Revolutionary War') (3,1,'C','The Civil War') (3,1,'D','World War I')
(3,2,'A','123') (3,2,'B','None') (3,2,'C','10') (3,2,'D','51')
(3,3,'A','Franklin D. Roosevelt') (3,3,'B','Dwight D. Eisenhower')
(3,3,'C','Harry Truman') (3,3,'D','Both A and C') (3,4,'A','Are
forced to work as slaves') (3,4,'B','Work for the common good')
(3,4,'C','Work from home computers') (3,4,'D','Don''t work')
(3,5,'A','John F. Kennedy') (3,5,'B','Franklin D. Roosevelt')
(3,5,'C','Abraham Lincoln') (3,5,'D','Ronald Reagan')
(3,5,'E','James A. Garfield') (3,7,'A','Siddharta Gautama')
(3,7,'B','Jesus Christ') (3,7,'C','Mahatma Gandhi')
(3,7,'D','Muhammad') (3,6,'A','Rhode Island') (3,6,'B','New
Hampshire') (3,6,'C','New Jersey') (3,6,'D','New York')
(3,9,'A','Islam') (3,9,'B','Hinduism') (3,9,'C','Christianity')
(3,9,'D','Buddhism') (3,10,'A','The Tiber River') (3,10,'B','The
Indus River') (3,10,'C','The Yellow River') (3,10,'D','The Nile
River') (1,1,'A','(D) & (E)') (1,1,'B',' (A) & (B)') (1,1,'C','(D)')
(1,1,'D','(A)') (1,1,'E','None of these') (1,2,'A','-17')
(1,2,'B','5') (1,2,'C','3') (1,2,'D','-5') (1,2,'E','None of these')
(1,3,'A','1.66') (1,3,'B','4') (1,3,'C','2') (1,3,'D','1')
(1,3,'E','None of these') (1,4,'A','x = 4, y = 1, z = 5') (1,4,'B',' x
= -7, y = 1, z = 5') (1,4,'C','x = 3, y = 2, z = 6') (1,4,'D',' x = 4, y = 2, z = 6') (1,4,'E',' x = 8, y = 2, z = 1') (1,5,'A','(C) & (D) ')
(1,5,'B',' (A), (B) & (C) ') (1,5,'C','(A), (B), (C) & (D)')
(1,5,'D','(A) & (B) ') (1,5,'E','None of the above')
(1,6,'A','\uffff') (1,6,'B','\u0000') (1,6,'C','" " (space)')
(1,6,'D','\u0001') (1,6,'E','None of the above') (1,7,'A','23')
(1,7,'B','Error. Cannot be executed.') (1,7,'C','57') (1,7,'D','11')
(1,7,'E','34') (1,8,'A','(A), (B) & (C)') (1,8,'B','(C)')
(1,8,'C','(A) & (B) ') (1,8,'D','(A)') (1,8,'E','(D)')
(1,9,'A','Boolean') (1,9,'B','Int') (1,9,'C','String')
(1,9,'D','Char') (1,9,'E','Byte') (1,10,'A','(A) & (C)')
(1,10,'B','(A) & (B)') (1,10,'C','(B) ') (1,10,'D','(B) & (D) ')
(1,10,'E','(D)') (1,11,'A','Integer "j" is not initialized.')
(1,11,'B','Nothing.') (1,11,'C','You cannot declare integer i inside
the for-loop declaration.') (1,11,'D','The syntax of the "if"
statement is incorrect.') (1,11,'E','You cannot print integer values
without converting them to strings.') (1,12,'A','Will compile and run
successfully ') (1,12,'B','Error. ClassA does not define a no-argument
constructor ') (1,12,'C','Error. There is no code in the constructor
ClassA(int x) ') (1,12,'D','Error. ClassB does not define a
no-argument constructor ') (1,12,'E','Error. There is no code in the
class ClassB ') (1,13,'A','(C) & (E) ') (1,13,'B','(B),(C) & (D)')
(1,13,'C','(A), (C) & (E)') (1,13,'D','All of these. ')
(1,13,'E','None of these. ') (1,14,'A','private ') (1,14,'B','public')
(1,14,'C','protected') (1,14,'D','private OR protected')
(1,14,'E','All of the above') (1,15,'A','(C), (D) & (E)')
(1,15,'B','(D) ') (1,15,'C','(A), (D) & (E)') (1,15,'D','(D) & (E) ')
(1,15,'E','(A)')
===== users data ====
(1,'1#gmail.com','','George','Ronald','','','Atlanta','GA','30303')
(2,'2#gmail.com','','Mary','Erikson','','','San Diego','CA','91901')
(3,'3#gmail.com','','John','Washington','','','Atlanta','GA','30314')
====enrolls data=====
(1,1,to_date('2012/02/15 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/22 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
(2,1,to_date('2012/02/15 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/22 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
(3,1,to_date('2012/02/17 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/24 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
(1,3,to_date('2012/02/17 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/24 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
(2,3,to_date('2012/02/20 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/27 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
(3,3,to_date('2012/02/20 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/27 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
===userResponse data====
(1,1,1,'A') (1,1,2,'B') (1,1,3,'A') (1,1,4,'B') (1,1,5,'N')
(1,1,6,'C') (1,1,7,'D') (1,1,8,'A') (1,1,9,'B') (1,1,10,'B')
(1,1,11,'A') (1,1,12,'B') (1,1,13,'A') (1,1,14,'A') (1,1,15,'A')
(2,1,1,'B') (2,1,2,'B') (2,1,3,'E') (2,1,4,'C') (2,1,5,'D')
(2,1,6,'A') (2,1,7,'C') (2,1,8,'B') (2,1,9,'B') (2,1,10,'A')
(2,1,11,'A') (2,1,12,'B') (2,1,13,'B') (2,1,14,'A') (2,1,15,'A')
(3,1,1,'C') (3,1,2,'C') (3,1,3,'D') (3,1,4,'D') (3,1,5,'A')
(3,1,6,'A') (3,1,7,'D') (3,1,8,'D') (3,1,9,'A') (3,1,10,'A')
(3,1,11,'B') (3,1,12,'B') (3,1,13,'A') (3,1,14,'A') (3,1,15,'C')
(1,3,1,'N') (1,3,2,'A') (1,3,3,'A') (1,3,4,'B') (1,3,5,'B')
(1,3,6,'C') (1,3,7,'D') (1,3,8,'A') (1,3,9,'A') (1,3,10,'B')
(2,3,1,'B') (2,3,2,'C') (2,3,3,'A') (2,3,4,'C') (2,3,5,'B')
(2,3,6,'D') (2,3,7,'D') (2,3,8,'D') (2,3,9,'A') (2,3,10,'A')
(3,3,1,'B') (3,3,2,'A') (3,3,3,'A') (3,3,4,'B') (3,3,5,'B')
(3,3,6,'C') (3,3,7,'D') (3,3,8,'A') (3,3,9,'A') (3,3,10,'B')
Thanks,
What I think you're asking is "how many questions did any user get right?" If so, based on the query you have - and the fact that there's no direct relation between users and questions - I've come up with the following:
select u.uno, sum(case ur.response when null then 0 else 1 end) as Test1
from question q
cross join users u
left join userresponse ur
on q.eno = ur.eno
and q.qno = ur.qno
and q.correctanswer = ur.response
and u.uno = ur.uno
where q.eno = '1'
group by u.uno
So we do a cartesion join between users and questions, because we don't have a better way to join them. We then do an left outer join against the userresponse table; unless everything matches correctly, the user either didn't answer the question or answered it wrong. We cast whether or not that value's null to a 0 if null and 1 if if it's not, so the sum of those is the number of correct answers per user.
If I've understood your query correctly, the following ought to work. It uses the old Oracle join syntax:
SELECT u.uno, COUNT(*)
FROM users u, userresponse ur, question q
WHERE u.uno = ur.uno
AND ur.response = q.correctanswer(+)
AND ur.eno = q.eno(+)
AND ur.qno = q.qno(+)
AND q.eno(+) = 1
GROUP BY u.uno
I think that you are trying to get all users and the associated quiz score. If I understood correctly, then using appropriate joins clauses, you can easily get the expected results:
select u.uno, count (ur.response) as NumberAnswered, count (q.correctanswer) as NumberCorrect
from users u
join userresponse ur --inner join means we limit user rows to users who have responses
on u.uno = ur.uno
left outer join question q --outer join means we look for row data, but don't exclude users based on the fact that the row doesn't match the join conditions
on ur.response = q.correctanswer
and q.eno = 1 --only include rows where the question.eno value is 1(?)
and q.eno = ur.eno --only include rows where question.eno and userresponse.eno are the same (the answer was correct)
group by u.uno

sql returning no rows selected

how can I make this sql query return zero for the count function instead of no rows selected?
select ur.uno, count(*)*5
from userresponse ur, question q
where ur.eno = q.eno
and q.correctanswer = ur.response
and q.qno = ur.qno
and ur.uno = '1'
and q.eno = '1'
group by ur.uno
q.correctanswer = ur.response is never true for this query that's what causes the no row selected, however I want to return zero.
sample data
Note:
- "||" is used to concatenate strings
- each string is between a pair of single quotes.
- each record is between "(" and ")".
- fields are ordered according to fields in tables
- "\n" means a new line
======exams data==========
(1,'Java Programming',60,1)
(3,'Elementary History',10,3)
======questions data===========
(1,1,'Choose the operations that can be performed on String
objects:(A) +\n(B) + =\n(C) -\n(D) %\n(E) ^','B')
(1,2,'What will be the result of the expression\na % b\nwhen a and b
are of type int and their values are a = -17 and b = -6?','A')
(1,3,'What will be the result of the expression\na % b\nwhen a and b
are of type int and their values are a = 10 and b = 6?','B')
(1,4,'Consider the following code:\nint x, y, z\ny = 1\nz = 5\nx = 0
- (++y) + z++\nAfter execution of this, what will be the values of x, y and z?','C')
(1,5,'Identify the statements that are correct:\n(A) int a = 13,
a>>2 = 3\n(B) int b = -8, b>>1 = -4\n(C) int a = 13, a>>>2 = 3\n(D)
int b = -8, b>>>1 = -4','E')
(1,6,'If not assigned a value, a variable of type char has the
following default value:','A')
(1,7,'What will be the value of a after execution of the following
statements:\nint a = 23, b = 34\na = ((a < b) ? (b + a) : (b -
a)','B')
(1,8,'Which of the following is not a hexadecimal number?\n(A)
999\n(B) (hex)23\n(C) 0x556\n(D) 0x1F2','C')
(1,9,'if(check4Biz(storeNum) != null) {}\nReferring to the above,
what datatype could be returned by method check4Biz()?','D')
(1,10,'Select the invalid assignment statements from the
following:\n(A) float x = 238.88\n(B) double y = 0x443\n(C) int n =
(int) true\n(D) long m =778645','A')
(1,11,'int j\nfor(int i=0i<14i++) {\nif(i<10) {\nj = 2 +
i\n}\nSystem.out.println("j: " + j + " i: " + i)\n}\nWhat is WRONG
with the above code?','E')
(1,12,'Consider the following code:\nclass ClassA\n{\npublic static
void main(String args [ ])\n{\nClassB b = classB()\n}\nClassA(int x) {
}\n}\nclass ClassB extends ClassA\n{\n}\nWhat will happen when we
compile and run this code?','A')
(1,13,'The keywords reserved but not used in the initial version of
Java are:\n(A) union\n(B) const\n(C) inner\n(D) goto\n(E) boolean\n(F)
synchronized','C')
(1,14,'We would like to make a member of a class visible in all
subclasses regardless of what package they are in. Which one of the
following keywords would achieve this?','D')
(1,15,'Which of the following are not keywords?\n(A) NULL\n(B)
implements\n(C) protected\n(D) extended\n(E) string','B')
(3,1,'The Battle of Gettysburg was fought during which war?','C')
(3,2,'Neil Armstrong and Buzz Aldrin walked how many \n' ||
'minutes on the moon in 1696?','B')
(3,3,'Which Presidents held office during World War II?','D')
(3,4,'In a communist economic system, people:','B')
(3,5,'Which president did not die while in office?','D')
(3,6,'Which state refused to attend the Constitutional Convention
\n' ||
'in 1787 because it didn''t want the United States government \n' ||
'to interfere with already established state affairs?','A')
(3,7,'Who founded Buddhism?','A')
(3,8,'Where is India?','D')
(3,9,'What is the dominant religion in India?','B')
(3,10,'Near which river did archaeologists find India''s \n' ||
'first civilization?','B')
========== answerOption data ============
(3,8,'A','Australia') (3,8,'B','America') (3,8,'C','Africa')
(3,8,'D','Asia') (3,1,'A','World War II') (3,1,'B','The
Revolutionary War') (3,1,'C','The Civil War') (3,1,'D','World War I')
(3,2,'A','123') (3,2,'B','None') (3,2,'C','10') (3,2,'D','51')
(3,3,'A','Franklin D. Roosevelt') (3,3,'B','Dwight D. Eisenhower')
(3,3,'C','Harry Truman') (3,3,'D','Both A and C') (3,4,'A','Are
forced to work as slaves') (3,4,'B','Work for the common good')
(3,4,'C','Work from home computers') (3,4,'D','Don''t work')
(3,5,'A','John F. Kennedy') (3,5,'B','Franklin D. Roosevelt')
(3,5,'C','Abraham Lincoln') (3,5,'D','Ronald Reagan')
(3,5,'E','James A. Garfield') (3,7,'A','Siddharta Gautama')
(3,7,'B','Jesus Christ') (3,7,'C','Mahatma Gandhi')
(3,7,'D','Muhammad') (3,6,'A','Rhode Island') (3,6,'B','New
Hampshire') (3,6,'C','New Jersey') (3,6,'D','New York')
(3,9,'A','Islam') (3,9,'B','Hinduism') (3,9,'C','Christianity')
(3,9,'D','Buddhism') (3,10,'A','The Tiber River') (3,10,'B','The
Indus River') (3,10,'C','The Yellow River') (3,10,'D','The Nile
River') (1,1,'A','(D) & (E)') (1,1,'B',' (A) & (B)') (1,1,'C','(D)')
(1,1,'D','(A)') (1,1,'E','None of these') (1,2,'A','-17')
(1,2,'B','5') (1,2,'C','3') (1,2,'D','-5') (1,2,'E','None of these')
(1,3,'A','1.66') (1,3,'B','4') (1,3,'C','2') (1,3,'D','1')
(1,3,'E','None of these') (1,4,'A','x = 4, y = 1, z = 5') (1,4,'B',' x
= -7, y = 1, z = 5') (1,4,'C','x = 3, y = 2, z = 6') (1,4,'D',' x = 4, y = 2, z = 6') (1,4,'E',' x = 8, y = 2, z = 1') (1,5,'A','(C) & (D) ')
(1,5,'B',' (A), (B) & (C) ') (1,5,'C','(A), (B), (C) & (D)')
(1,5,'D','(A) & (B) ') (1,5,'E','None of the above')
(1,6,'A','\uffff') (1,6,'B','\u0000') (1,6,'C','" " (space)')
(1,6,'D','\u0001') (1,6,'E','None of the above') (1,7,'A','23')
(1,7,'B','Error. Cannot be executed.') (1,7,'C','57') (1,7,'D','11')
(1,7,'E','34') (1,8,'A','(A), (B) & (C)') (1,8,'B','(C)')
(1,8,'C','(A) & (B) ') (1,8,'D','(A)') (1,8,'E','(D)')
(1,9,'A','Boolean') (1,9,'B','Int') (1,9,'C','String')
(1,9,'D','Char') (1,9,'E','Byte') (1,10,'A','(A) & (C)')
(1,10,'B','(A) & (B)') (1,10,'C','(B) ') (1,10,'D','(B) & (D) ')
(1,10,'E','(D)') (1,11,'A','Integer "j" is not initialized.')
(1,11,'B','Nothing.') (1,11,'C','You cannot declare integer i inside
the for-loop declaration.') (1,11,'D','The syntax of the "if"
statement is incorrect.') (1,11,'E','You cannot print integer values
without converting them to strings.') (1,12,'A','Will compile and run
successfully ') (1,12,'B','Error. ClassA does not define a no-argument
constructor ') (1,12,'C','Error. There is no code in the constructor
ClassA(int x) ') (1,12,'D','Error. ClassB does not define a
no-argument constructor ') (1,12,'E','Error. There is no code in the
class ClassB ') (1,13,'A','(C) & (E) ') (1,13,'B','(B),(C) & (D)')
(1,13,'C','(A), (C) & (E)') (1,13,'D','All of these. ')
(1,13,'E','None of these. ') (1,14,'A','private ') (1,14,'B','public')
(1,14,'C','protected') (1,14,'D','private OR protected')
(1,14,'E','All of the above') (1,15,'A','(C), (D) & (E)')
(1,15,'B','(D) ') (1,15,'C','(A), (D) & (E)') (1,15,'D','(D) & (E) ')
(1,15,'E','(A)')
===== users data ====
(1,'1#gmail.com','','George','Ronald','','','Atlanta','GA','30303')
(2,'2#gmail.com','','Mary','Erikson','','','San Diego','CA','91901')
(3,'3#gmail.com','','John','Washington','','','Atlanta','GA','30314')
====enrolls data=====
(1,1,to_date('2012/02/15 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/22 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
(2,1,to_date('2012/02/15 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/22 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
(3,1,to_date('2012/02/17 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/24 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
(1,3,to_date('2012/02/17 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/24 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
(2,3,to_date('2012/02/20 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/27 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
(3,3,to_date('2012/02/20 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/27 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
===userResponse data====
(1,1,1,'A') (1,1,2,'B') (1,1,3,'A') (1,1,4,'B') (1,1,5,'N')
(1,1,6,'C') (1,1,7,'D') (1,1,8,'A') (1,1,9,'B') (1,1,10,'B')
(1,1,11,'A') (1,1,12,'B') (1,1,13,'A') (1,1,14,'A') (1,1,15,'A')
(2,1,1,'B') (2,1,2,'B') (2,1,3,'E') (2,1,4,'C') (2,1,5,'D')
(2,1,6,'A') (2,1,7,'C') (2,1,8,'B') (2,1,9,'B') (2,1,10,'A')
(2,1,11,'A') (2,1,12,'B') (2,1,13,'B') (2,1,14,'A') (2,1,15,'A')
(3,1,1,'C') (3,1,2,'C') (3,1,3,'D') (3,1,4,'D') (3,1,5,'A')
(3,1,6,'A') (3,1,7,'D') (3,1,8,'D') (3,1,9,'A') (3,1,10,'A')
(3,1,11,'B') (3,1,12,'B') (3,1,13,'A') (3,1,14,'A') (3,1,15,'C')
(1,3,1,'N') (1,3,2,'A') (1,3,3,'A') (1,3,4,'B') (1,3,5,'B')
(1,3,6,'C') (1,3,7,'D') (1,3,8,'A') (1,3,9,'A') (1,3,10,'B')
(2,3,1,'B') (2,3,2,'C') (2,3,3,'A') (2,3,4,'C') (2,3,5,'B')
(2,3,6,'D') (2,3,7,'D') (2,3,8,'D') (2,3,9,'A') (2,3,10,'A')
(3,3,1,'B') (3,3,2,'A') (3,3,3,'A') (3,3,4,'B') (3,3,5,'B')
(3,3,6,'C') (3,3,7,'D') (3,3,8,'A') (3,3,9,'A') (3,3,10,'B')
Then it sounds like you want to do an outer join
select ur.uno, count(q.eno)*5
from userresponse ur
left outer join question q
on( ur.eno = q.eno
and q.correctanswer = ur.response
and q.qno = ur.qno
and q.eno = '1')
where ur.uno = '1'
group by ur.uno
This will return a row for every row in userresponse with a uno of '1' with a count(*) of 0 if there are no matching rows in question.
Try out above Query with ISNULL function:
select ur.uno, NVL(count(*)*5,0)
from userresponse ur, question q
where ur.eno = q.eno
and q.correctanswer = ur.response
and q.qno = ur.qno
and ur.uno = '1'
and q.eno = '1'
group by ur.uno
when ever AND Operator are implementing with the different value on the same column with equality operator the overall condition return NO ROW as AND Operator evaluate on a 1 to 1 with direction towards table to the column...............