How to use find by sql and binds? - sql

I'm been staring at my code for over an hour and I still can't figure out whats wrong with my query.
I'm getting the error message:
ActiveRecord::StatementInvalid: PG::SyntaxError: ERROR: syntax error at or near ")"
LINE 38: WHERE (abs(ax2 - ?) / ? < ?)
query = %Q{
SELECT
avg(ax2),
avg(ay2),
avg(az2)
FROM (
SELECT
avg(t1) as t2,
avg(n1) as n2,
avg(ax1) as ax2,
avg(ay1) as ay2,
avg(az1) as az2
FROM (
SELECT
avg(t) as t1,
avg(n) as n1,
avg(ax) as ax1,
avg(ay) as ay1,
avg(az) as az1
FROM obds
WHERE uid = #{uid} AND (ev = 6011 or ev = 6012)
GROUP BY
round(t,3),
round(n,3)
)
AS derivedTable1
GROUP BY round(t1 + 0.0005,3), round(n1 + 0.0005,3)
)
AS derivedTable2
WHERE (abs(ax2 - ?) / ? < ?) #<<<<< Line with error
}
binds = [ uid, x_average, x_average, THRESHOLD_FOR_RESTING ]
result = Ozd.find_by_sql query, binds

The answer is that the query has to be apart of the bind array.
binds = [ query, uid, x_average, x_average, THRESHOLD_FOR_RESTING ]
results = Ozd.find_by_sql binds

try this WHERE (abs((ax2 - ?) / ? < ?)) instead

Related

Cannot cast result from Sub-Select to numeric

I am selecting a list of IDs as a sub-query in a condition but it says it cannot convert '123,456' to numeric. The problem occurs in the last line. DB is Sybase-SQL-Anywhere.
SELECT
ISNULL(SUM(a.menge), 0) AS menge,
ISNULL(SUM(a.wert), 0) AS wert
FROM admin.p_ws_ix_kontrakte_ernte_auswertung_jensek a
WHERE
(a.KtrErnteJahr = ? OR ? IS NULL)
AND (
(a.KtrDispoKennz >= ? OR ? IS NULL)
AND
(a.KtrDispoKennz <= ? OR ? IS NULL)
)
AND a.artikelstammid IN ((SELECT LIST(artikelstammId) FROM admin.ws_ix_auswertung_cfg_spalten_artikel WHERE columnId = $column))
Remove the LIST():
# replace this:
AND a.artikelstammid IN ((SELECT LIST(artikelstammId) FROM admin.ws_ix_auswertung_cfg_spalten_artikel WHERE columnId = $column))
# with this:
AND a.artikelstammid IN (SELECT artikelstammId FROM admin.ws_ix_auswertung_cfg_spalten_artikel WHERE columnId = $column)
Another option would be an exists/correlated subquery:
# replace this:
AND a.artikelstammid IN ((SELECT LIST(artikelstammId) FROM admin.ws_ix_auswertung_cfg_spalten_artikel WHERE columnId = $column))
# with this:
AND exists (SELECT 1 FROM admin.ws_ix_auswertung_cfg_spalten_artikel b WHERE b.columnId = $column and b.artikelstammId = a.artikelstammid)

Why is "[COUNT (*): 0]" returned instead of just "0" when executing sql query in groovy?

Why is "[COUNT (*): 0]" returned instead of just "0" when executing sql query in groovy? What can I do to return only a number?
def res = sql.firstRow("""SELECT count(*) FROM bd.pas WHERE INN = ?
AND SYSDATE >= RECDATEBEGIN AND SYSDATE < RECDATEEND AND NVL(DLL, 0) = 0
""",['test'])
println(res)
Use an alias in your query:
def res = sql.firstRow("""SELECT count(*) as num FROM bd.pas WHERE INN = ?
AND SYSDATE >= RECDATEBEGIN AND SYSDATE < RECDATEEND AND NVL(DLL, 0) = 0
""",['test'])
and then read the specific field:
println(res.num)
The firstRow() returns a GroovyRowResult which is essentially a Map.
That's why you get [COUNT (*): 0].
To get a number only out of it you can do:
def res = sql.firstRow("""SELECT count(*) FROM bd.pas ...""",['test']).values().first()

sql distinct statement not working in powershel script

I am trying to run the following sql command on a powershell script:
I set the following as a variable:
$DBSUM = select x.[example 1], y.example2, z.example3
from (select count (distinct valueA) AS "example 1"
from dbo.table1
) as x,
(select count (distinct ValueB) AS "example2"
from dbo.table2
) as y,
(select count (distinct ValueC) AS "example3"
from dbo.table3
) as z
after some other commands, i have the following:
$SqlConnectionSUM = New-Object System.Data.SqlClient.SqlConnection
$SqlConnectionSUM.ConnectionString = "Server = $SQLServer; Database =
$SQLDB; Integrated Security = True"
$SqlCmdSUM = New-Object System.Data.SqlClient.SqlCommand
$SqlCmdSUM.CommandText = $DBSUM
$SqlCmdSUM.Connection = $SqlConnectionSUM
$SqlAdapterSUM = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapterSUM.SelectCommand = $SqlCmdSUM
$DataSetSUM = New-Object System.Data.DataSet
$null = $SqlAdapterSUM.Fill($DataSetSUM)
$DataSetSUM.Tables[0] | select * -ExcludeProperty RowError, RowState,
HasErrors, ItemArray,Table | ConvertTo-Html -Head $HtmlHead | Out-File
"$PSScriptRoot\filelocation\example.html"
The above command works perfectly in SQL, but when I run on my powershell I get the error:
+ ... .example3 from (select count (distinct ValueA) AS "example1 ...
+ ~~~~~~
Unexpected token 'example' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken
Please can anyone advise?
Thank you.
Thank you to Luuk and Astentx for your replies.
I have now working ok, the issue was the " and spaces on example 1
I replaced the spaces with _ and removed the " and t works absolutely fine.
Here is the result:
$DBSUM = select x.example_1, y.example2, z.example3
from (select count (distinct valueA) AS example_1
from dbo.table1
) as x,
(select count (distinct ValueB) AS example2
from dbo.table2
) as y,
(select count (distinct ValueC) AS example3
from dbo.table3
) as z
Thank you all.

Using raw DB to query but fails to run because sql string has an error

Im new to using laravel and i have to query using the an sql string but the code fails to run because there is an error in the sql query
The code is:
$current_lat = $request->latitude;
$current_lng = $request->longitude;
$car_type = $request->car_type;
$data=DB::table('artisantypes')->select(DB::raw('artisantypes.max_seat AS max_size,3956 * 2 * ASIN(SQRT(POWER(SIN(($current_lat - artisans.driver_lat) * pi()/180 / 2), 2)+ COS($current_lat * pi()/180 ) * COS(artisans.driver_lat * pi()/180) * POWER(SIN(($current_lng - artisans.driver_lng) * pi()/180 / 2), 2) )) as distance,artisans.driver_lat,artisans.driver_lng' ))
->leftjoin('artisans','artisantypes.id', '=','artisans.car_id' )
->where('artisantypes.id' ,'=', $car_type and 'artisans.status', '=' , 0)
->groupby('artisans.id')
->having('distance' ,'<', 25)
->orderby ('distance', 'ASC' )
->limit( 0,1)
->get();
The Error in got is :
check the manual that corresponds to your MariaDB server version for the right syntax to use near '= `artisantypes`.`id` = ? group by `artisans`.`id` having `distance` < ?
You cannot directly specify an AND in the where function.
change
->where('artisantypes.id' ,'=', $car_type and 'artisans.status', '=' , 0)
to
->where([
['artisantypes.id' ,'=', $car_type],
['artisans.status', '=' , 0],
])

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 ;