sql distinct statement not working in powershel script - sql

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.

Related

can't execute mysql request via R

I am having difficulty. I need to get the desired result through mysql query in R .
my attempt.
load libraries which i use.
library(RMySQL)
library(data.table)
library(dplyr)
library(Rcpp)
library(zoo)
library(gsubfn)
library(proto)
library(RSQLite)
library(DBI)
library(RMariaDB)
library(dbx)
then i try perform connect
getDf <- function (connect, sql)
{
str(paste("EXECUTE: ", sql))
query <- dbSendQuery(connect, sql)
df <- dbFetch(query, n = -1)
dbClearResult(query)
str(paste("ROW FETCHED:", nrow(df)))
df
}
then
db_user <- 'k'
db_password <- 'F'
db_name <- 'yyy'
db_table <- 'mytable'
db_host <- 'xxx' # for local access
db_port <- 3306
readDB <- dbConnect(RMariaDB::MariaDB(), user = db_user, pass = db_password, dbname = db_name, host = db_host, port = db_port)
and here i try get prepared data via query mysql
df333 <- getDf(readDB, paste("UPDATE incoming_aggregation_google ia
JOIN data_aggregation_google_median dm ON
(ia.agency_id = dm.agency_id)
AND (ia.search_category_id = dm.search_category_id)
AND (ia.offer_category_id = dm.offer_category_id)
AND (ia.flight_codes = dm.flight_codes)
AND (ia.search_type_category_id = dm.search_type_category_id)
SET ia.prediction_diff_percent_base_price = dm.median_diff_percent_base_price + (0.4 * RAND() - 0.2);
UPDATE incoming_aggregation_google_general ia
JOIN data_aggregation_google_general_median dm ON
(ia.agency_id = dm.agency_id)
AND (ia.offer_category_id = dm.offer_category_id)
AND (ia.search_type_category_id = dm.search_type_category_id)
AND (ia. service_discount_category_id = dm. service_discount_category_id)
SET ia.prediction_diff_percent_base_price = dm.median_diff_percent_base_price + (0.4 * RAND() - 0.2);
UPDATE incoming_aggregation_google_general da
JOIN data_aggregation_google_general_median i ON
(
i.agency_id=da.agency_id
AND i.offer_category_id=da.offer_category_id
AND i.service_discount_category_id=da.service_discount_category_id
AND i.search_type_category_id=da.search_type_category_id
)
set da.prediction_diff_percent_base_price = i.median_diff_percent_base_price;", db_table))
but the error
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE incoming_aggregation_google_general ia
JOIN data_aggregation_google_gener' at line 9 [1064]
Please help me understand what I did wrong and how to fix it? If what I want to do is not can be done, is there a way to translate the essence of this query into logic R.
Thanks for your any valuable 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 ;

How to use find by sql and binds?

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

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']]

powershell to read multiple lines of sql

I currently have a powershell script that looks like this:
$Query = "SELECT
t1.BSM_NM
,t1.D_DTM AS MAXDATETIME
,t1.TECHNOLOGY
,t1.VOICEDATA
,CASE
WHEN t1.VOICEDATA = 'VOICE'
AND
(
t1.CUST_BLK_CNT/t1.ATT_CNT >= t2.MAJOR_VOICE_BLOCK AND t1.CUST_BLK_CNT/t1.ATT_CNT < t2.CRITICAL_VOICE_BLOCK
OR
t1.DRP_CALL_CNT/t1.ATT_CNT >= t2.MAJOR_VOICE_DROP AND t1.DRP_CALL_CNT/t1.ATT_CNT < t2.CRITICAL_VOICE_DROP
OR
t1.AXS_F_CNT/t1.ATT_CNT >= t2.MAJOR_VOICE_AXSFAIL AND t1.AXS_F_CNT/t1.ATT_CNT < t2.CRITICAL_VOICE_AXSFAIL
)
THEN 1
WHEN t1.VOICEDATA = 'DATA'
AND
(
t1.CUST_BLK_CNT/t1.ATT_CNT >= t2.MAJOR_VOICE_BLOCK AND t1.CUST_BLK_CNT/t1.ATT_CNT < t2.CRITICAL_DATA_BLOCK
OR
t1.DRP_CALL_CNT/t1.ATT_CNT >= t2.MAJOR_VOICE_DROP AND t1.DRP_CALL_CNT/t1.ATT_CNT < t2.CRITICAL_DATA_DROP
OR
t1.AXS_F_CNT/t1.ATT_CNT >= t2.MAJOR_VOICE_AXSFAIL AND t1.AXS_F_CNT/t1.ATT_CNT < t2.CRITICAL_DATA_AXSFAIL
)
THEN 1
WHEN t1.VOICEDATA = 'VOICE'
AND
(
t1.CUST_BLK_CNT/t1.ATT_CNT >= t2.CRITICAL_VOICE_BLOCK
OR
t1.DRP_CALL_CNT/t1.ATT_CNT >= t2.CRITICAL_VOICE_DROP
OR
t1.AXS_F_CNT/t1.ATT_CNT >= t2.CRITICAL_VOICE_AXSFAIL
)
THEN 2
WHEN t1.VOICEDATA = 'DATA'
AND
(
t1.CUST_BLK_CNT/t1.ATT_CNT >= t2.CRITICAL_DATA_BLOCK
OR
t1.DRP_CALL_CNT/t1.ATT_CNT >= t2.CRITICAL_DATA_DROP
OR
t1.AXS_F_CNT/t1.ATT_CNT >= t2.CRITICAL_DATA_AXSFAIL
)
THEN 2
ELSE 0
END MAJORCRITICAL
FROM DS3R_FH_ALL_TRIGGER_VIEW t1
INNER JOIN
ZDMSN.DS3R_1XRTT_TRIGGERS_THRESHOLD t2
ON
t1.BSM_NM = t2.BSC_NM
AND
t1.TECHNOLOGY = t2.TECHNOLOGY
WHERE t1.BSM_NM = 'ARL1' and t1.D_DTM = (SELECT MAX(D_DTM) FROM DS3R_FH_1XRTT_BTS_LVL_KPI WHERE BSM_NM = 'ARL1')"
$data_set = new-object system.data.dataset
$adapter = new-object system.data.oracleclient.oracledataadapter ($Query, $Connection)
[void] $adapter.Fill($data_set)
$table = new-object system.data.datatable
$table = $data_set.Tables[0]
$bsmNM = $data_set.Tables[0].Rows[0].BSM_NM
$maxDT = $data_set.Tables[0].Rows[0].MAXDATETIME
$majorC = $data_set.Tables[0].Rows[0].MAJORCRITICAL
$table | Select MAJORCRITICAL
{
if ($majorC -match "*2*" -and $majorC -match "*1*")
if ($majorC -match "*1*" )
if ($majorC -match "*2*")
the results came back as such:
it doesn't error but it doesn't seem to be doing what I want it to do. If there is a value of 1 in any of the rows in the MAJORCRITICAL column, I want it to do the 2nd if statement, if there is a 1 in one row and a 2 in another row, I want it to do the 1st if statement. The code runs, but the if statements aren't running...
You are only looking at the first row in your example, as you are not doing foreach or similar.
Additionally you need to use $_ to refer to the current item in foreach (alias %)