Using STUFF Function - subquery

I've this table TableA that have these fields: [intIdEntidad],[intIdEjercicio],[idTipoGrupoCons]. The tableA look like for idTipoGrupoCons = 16 this image
enter image description here
I'm trying to use STUFF function to show the column intIdEjercicio separated by coma, something like this;
enter image description here
This is query I'm using to obtain result the above image:
SELECT DISTINCT o.idTipoGrupoCons, o.intIdEntidad, ejercicios= STUFF((
SELECT ', ' + CONVERT(VARCHAR,a.intIdEjercicio)
FROM dbo.[tbEntidades_Privadas_InfoAdicionalGrupo] AS a
WHERE a.idTipoGrupoCons = 16
FOR XML PATH, TYPE).value(N'.[1]', N'varchar(max)'), 1, 2, '')
FROM [tbEntidades_Privadas_InfoAdicionalGrupo] AS o
JOIN tbEntidades_Privadas p On O.intIdEntidad = p.intIdEntidad
WHERE o.idTipoGrupoCons = 16
The result isn't correct, because I execute this query for idTipoGrupoCons = 16
SELECT [idTipoGrupoCons], [intIdEntidad],[intIdEjercicio]
FROM [tbEntidades_Privadas_InfoAdicionalGrupo] A
WHERE A.idTipoGrupoCons = 16
The result is this
enter image description here
It's means that for intIdEntidad = 50 intIdEjercicio is just 7 and for intIdEntidad = 45 intIdEjercicio = 2 and 4
I suppose that the problem is that I need to add a subquery to or a function into STUFF or in the outer WHERE to add condition to intIdEntidad each time to call STUFF function.
I've read about the use of CROSS APPLY and perhaps it can be used to solve the problem

Here is the answer.
The problem was that need to join tableA with the same table into the STUFF function. At the end the query look like this:
SELECT t1.idTipoGrupoCons, t1.intIdEntidad,
,ejercicios = STUFF(
(SELECT ', ' + t3.Ejercicio
FROM [tbEntidades_Privadas_InfoAdicionalGrupo] t2
JOIN tbMtoNoRegistro_Ejercicios t3 ON t2.intIdEjercicio = e.intEjercicio
WHERE t2.idTipoGrupoCons = t1.idTipoGrupoCons
AND t2.intIdEntidad = t1.intIdEntidad
ORDER BY t3.Ejercicio
FOR XML PATH ('')
)
,1,2,'')
FROM [tbEntidades_Privadas_InfoAdicionalGrupo] t1
JOIN tbEntidades_Privadas p ON t1.intIdEntidad = p.intIdEntidad
WHERE t1.idTipoGrupoCons = 17
GROUP BY t1.idTipoGrupoCons,t1.intIdEntidad, p.strDenominacionSocial

Related

how to insert multiple rows into sqllite3 database

I am trying to select rows and fetch them from the DB table and then insert them into a list so I can insert all of the rows at once into the database, but I got an error.
def paid_or_returned_buyingchecks(self):
date = datetime.now()
now = date.strftime('%Y-%m-%d')
self.tenlistchecks=[]
self.con = sqlite3.connect('car dealership.db')
self.cursorObj = self.con.cursor()
self.dashboard_buying_checks_dates = self.cursorObj.execute("select id, paymentdate , paymentvalue, car ,sellername from cars_buying_checks where nexttendays=?",(now,))
self.dashboard_buying_checks_dates_output = self.cursorObj.fetchall()
self.tenlistchecks.append(self.dashboard_buying_checks_dates_output)
print(self.tenlistchecks)
self.dashboard_buying_checks_dates = self.cursorObj.executemany("insert into paid_buying_checks VALUES(?,?,?,?,?)",[self.tenlistchecks])
self.con.commit()
but I got an error :
[[(120, '21-08-2022', '1112', 'Alfa Romeo', 'james'), (122, '21-08-2022', '465', 'Buick', 'daniel '), (123, '21-08-2022', '789', 'Buick', 'daniel ')]]
self.dashboard_buying_checks_dates = self.cursorObj.executemany(
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 5, and there are 1 supplied.
self.cursorObj.fetchall() returns a list of tuples, which is what you need to feed to executemany, so
self.cursorObj.executemany("insert into paid_buying_checks VALUES(?,?,?,?,?)",self.tenlistchecks)
not
self.cursorObj.executemany("insert into paid_buying_checks VALUES(?,?,?,?,?)",[self.tenlistchecks])

Calculate percentage change in pandas with rows that contain the same values

I am using Pandas to calculate percentage change(s) between values that occur more than once in the column of interest.
I want to compare the values of last weeks workout provided they're the same exercise type to get the percentage change of (weight used, reps accomplished )
I am able to get the percentages of all the rows which is halfway what I want but the conditional part is missing - so only get the percentages if the exercise_name is of the same value as we want to compare how we improve on a weekly, bi-weekly basis.
ids = self.user_data["exercise"].fillna(0)
dups = self.user_data[ids.isin(ids[ids.duplicated()])].sort_values("exercise")
dups['exercise'] = dups['exercise'].astype(str)
dups['set_one_weight'] = pd.to_numeric(dups['set_one_weight'])
dups['set_two_weight'] = pd.to_numeric(dups['set_two_weight'])
dups['set_three_weight'] = pd.to_numeric(dups['set_three_weight'])
dups['set_four_weight'] = pd.to_numeric(dups['set_four_weight'])
dups['set_one'] = pd.to_numeric(dups['set_one'])
dups['set_two'] = pd.to_numeric(dups['set_two'])
dups['set_three'] = pd.to_numeric(dups['set_three'])
dups['set_four'] = pd.to_numeric(dups['set_four'])
**percent_change = dups[['set_three_weight']].pct_change()**
the last line gets the percentage change for all the rows for column set_three_weight but is unable to do what I want above which is find rows with same name and obtain the percentage change.
UPDATE
Using Group By Solution
ids = self.user_data["exercise"].fillna(0)
dups = self.user_data[ids.isin(ids[ids.duplicated()])].sort_values("exercise")
dups['exercise'] = dups['exercise'].astype(str)
dups['set_one_weight'] = pd.to_numeric(dups['set_one_weight'])
dups['set_two_weight'] = pd.to_numeric(dups['set_two_weight'])
dups['set_three_weight'] = pd.to_numeric(dups['set_three_weight'])
dups['set_four_weight'] = pd.to_numeric(dups['set_four_weight'])
dups['set_one'] = pd.to_numeric(dups['set_one'])
dups['set_two'] = pd.to_numeric(dups['set_two'])
dups['set_three'] = pd.to_numeric(dups['set_three'])
dups['set_four'] = pd.to_numeric(dups['set_four'])
dups['routine_upload_date'] = pd.to_datetime(dups['routine_upload_date'])
# percent_change = dups[['set_three_weight']].pct_change()
# Group the exercises together and create a new cols that represent the percentage delta variation in percentages
dups.sort_values(['exercise', 'routine_upload_date'], inplace=True, ascending=[True, False])
dups['set_one_weight_delta'] = (dups.groupby('exercise')['set_one_weight'].apply(pd.Series.pct_change) + 1)
dups['set_two_weight_delta'] = (dups.groupby('exercise')['set_two_weight'].apply(pd.Series.pct_change) + 1)
dups['set_three_weight_delta'] = (dups.groupby('exercise')['set_three_weight'].apply(pd.Series.pct_change) + 1)
dups['set_four_weight_delta'] = (dups.groupby('exercise')['set_four_weight'].apply(pd.Series.pct_change) + 1)
dups['set_one_reps_delta'] = (dups.groupby('exercise')['set_one'].apply(pd.Series.pct_change) + 1)
dups['set_two_reps_delta'] = (dups.groupby('exercise')['set_two'].apply(pd.Series.pct_change) + 1)
dups['set_three_reps_delta'] = (dups.groupby('exercise')['set_three'].apply(pd.Series.pct_change) + 1)
dups['set_four_reps_delta'] = (dups.groupby('exercise')['set_four'].apply(pd.Series.pct_change) + 1)
print(dups.head())
I think this gets me the result(s) I want, would like someone to confirm

Python pyodbc fetchmany() how to select out put to update query

I have code to fetchmany() that will output eg:10 records
And i have added iterating value for each 0 1 2 3 4 5 for print statement , now i want user input 0 or 1 and it should select column. For those input so i can update sql record for those column
cur.execute("select events.SERIALNUM, emp.LASTNAME, emp.SSNO,
events.EVENT_TIME_UTC from AccessControl.dbo.emp,
AccessControl.dbo.events where emp.id = events.empid and emp.SSNO=?
order by EVENT_TIME_UTC desc ", empid)
rows = cur.fetchmany(att_date)
n = 0
for row in rows :
event_date = row.EVENT_TIME_UTC
utc = event_date.replace(tzinfo=from_zone)
utc_to_local = utc.astimezone(to_zone)
local_time = utc_to_local.strftime('%H:%M:%S')
att_date = utc_to_local.strftime('%d:%m:%y')
print (n, row.SERIALNUM, row.LASTNAME, row.SSNO, att_date, local_time)
n = n + 1
seri_al = input("Copy And Past the serial number u want to modifiy: ")
this will output following Data
0 1500448188 FIRST NAME 03249 2017-07-19 17:01:17
1 1500448187 FIRST NAME 03249 2017-07-19 17:01:15
Eg:
seri_al = input("Copy And Past the serial number u want to modifiy: ")
instead of copying and pasting '1500448188' these numbers I want the user to only enter '0' and map that one and update sql query as for where clause serial number.
It appears that you already know how to use input to prompt for the user's choice. The only piece you are missing is to add items to a dictionary as you loop through the rows. Here is a slightly abstracted example:
rows = [('1500448188',),('1500448187',)] # test data
selections = dict()
n = 0
for row in rows:
selections[n] = row[0]
print(n, repr(row[0]))
n += 1
select = input("Enter the index (0, 1, ...) you want to select: ")
selected_key = selections[int(select)]
print("You selected " + repr(selected_key))
which prints
0 '1500448188'
1 '1500448187'
Enter the index (0, 1, ...) you want to select: 1
You selected '1500448187'

Split a string on sqlite

i don't know sqlite but I have to implement a database already done. I'm programming with Corona SDK. The problem: i have a column called "answers" in this format: House,40|Bed,20|Mirror,10 ecc.
I want to split the string and remove "," "|" like this:
VARIABLE A=House
VARIABLE A1=40
VARIABLE B=Bed
VARIABLE B1=20
VARIABLE C=Mirror
VARIABLE C1=10
I'm sorry for my english. Thanks to everybody.
Try this:
If you want to simply remove the characters, then you can use the following:
Update 3 :
local myString = "House;home;flat,40|Bed;bunk,20|Mirror,10"
local myTable = {}
local tempTable = {}
local count_1 = 0
for word in string.gmatch(myString, "([^,|]+)") do
myTable[#myTable+1]=word
count_1=count_1+1
tempTable[count_1] = {} -- Multi Dimensional Array
local count_2 = 0
for word_ in string.gmatch(myTable[#myTable], "([^,|,;]+)") do
count_2=count_2+1
local str_ = word_
tempTable[count_1][count_2] = str_
--print(count_1.."|"..count_2.."|"..str_)
end
end
print("------------------------")
local myTable = {} -- Resetting my table, just for using it again :)
for i=1,count_1 do
for j=1,#tempTable[i] do
print("tempTable["..i.."]["..j.."] = "..tempTable[i][j])
if(j==1)then myTable[i] = tempTable[i][j] end
end
end
print("------------------------")
for i=1,#myTable do
print("myTable["..i.."] = "..myTable[i])
end
--[[ So now you will have a multidimensional array tempTable with
elements as:
tempTable = {{House,home,flat},
{40},
{Bed,bunk},
{20},
{Mirror},
{10}}
So you can simply take any random/desired value from each.
I am taking any of the 3 from the string "House,home,flat" and
assigning it to var1 below:
--]]
var1 = tempTable[1][math.random(3)]
print("var1 ="..var1)
-- So, as per your need, you can check var1 as:
for i=1,#tempTable[1] do -- #tempTable[1] means the count of array 'tempTable[1]'
if(var1==tempTable[1][i])then
print("Ok")
break;
end
end
----------------------------------------------------------------
-- Here you can print myTable(if needed) --
----------------------------------------------------------------
for i=1,#myTable do
print("myTable["..i.."]="..myTable[i])
end
--[[ The output is as follows:
myTable[1]=House
myTable[2]=40
myTable[3]=Bed
myTable[4]=20
myTable[5]=Mirror
myTable[6]=10
Is it is what you are looking for..?
]]--
----------------------------------------------------------------
Keep coding............. :)

What is the maximum number of parameters I can use in a subsonic 2.1+ 'IN' statment?

I think i am hitting a limit. I have two IN statements in the SQL generated by subsonic. Or am I hitting the varchar ( 8000 ) limit?
When I send i fewer parameters, the statement returns results, when I send in more, the result set comes back blank.
Below is what I am catching in SQL Profiler:
exec sp_executesql N'/* GetDataSet() */
SELECT
[dbo].[QuoteDBAll].[quote_id],
[dbo].[conn_quote_result].[product_category_name],
part_number,
quote_result_special_price * ( quote_result_quantity + quote_result_quantity_spare) AS Total,
company_name
FROM [dbo].[QuoteDBAll]
INNER JOIN [dbo].[conn_quote_result]
ON [dbo].[QuoteDBAll].[quote_number] = [dbo].[conn_quote_result].[quote_number]
INNER JOIN [dbo].[conn_company]
ON [dbo].[QuoteDBAll].[company_id] = [dbo].[conn_company].[company_id]
GROUP BY [dbo].[QuoteDBAll].[quote_id],
[dbo].[conn_quote_result].[product_category_name],
[dbo].[conn_quote_result].[part_number],
[dbo].[conn_quote_result].[quote_result_quantity],
[dbo].[conn_quote_result].[quote_result_quantity_spare],
[dbo].[conn_quote_result].[quote_result_special_price],
[dbo].[QuoteDBAll].[quote_status_id],
company_name
HAVING (quote_status_id = #quote_status_id0)
AND (company_name IN
(#in1,#in2,#in3,#in4,#in5,#in6,#in7,#in8,#in9,#in10,
#in11,#in12,#in13,#in14,#in15,#in16,#in17,#in18,#in19,#in20,
#in21,#in22,#in23,#in24,#in25,#in26,#in27,#in28,#in29,#in30,#in31))
AND ([dbo].[conn_quote_result].[product_category_name] IN
(#in1,#in2,#in3,#in4,#in5,#in6,#in7,#in8,#in9,#in10,
#in11,#in12,#in13,#in14,#in15,#in16,#in17,#in18,#in19,#in20,
#in21,#in22,#in23,#in24,#in25,#in26,#in27,#in28,#in29,#in30,
#in31,#in32,#in33,#in34,#in35,#in36,#in37,#in38))',
N'#quote_status_id0 varchar(1),### varchar(8000),#in1 varchar(15),#in2 varchar(22),
#in3 varchar(21),#in4 varchar(13),#in5 varchar(5),#in6 varchar(6),#in7 varchar(13),
#in8 varchar(25),#in9 varchar(8),#in10 varchar(14),#in11 varchar(9),#in12 varchar(11),
#in13 varchar(16),#in14 varchar(12),#in15 varchar(14),#in16 varchar(16),
#in17 varchar(11),#in18 varchar(15),#in19 varchar(6),#in20 varchar(12),
#in21 varchar(12),#in22 varchar(10),#in23 varchar(15),#in24 varchar(15),
#in25 varchar(15),#in26 varchar(11),#in27 varchar(16),#in28 varchar(20),
#in29 varchar(6),#in30 varchar(16),#in31 varchar(17),#in32 varchar(11),
#in33 varchar(18),#in34 varchar(23),#in35 varchar(14),#in36 varchar(19),
#in37 varchar(12),#in38 varchar(14)',
#quote_status_id0 = '1', ### = NULL, #in1 = 'Widget1', #in2 = 'Widget2',
#in3 = 'Widget3', #in4 = 'Widget4', #in5 = 'Widget5', #in6 = 'Widget6', #in7 = 'Widget7',
#in8 = 'Widget7', #in9 = 'Widget7', #in10 = 'Widget8', #in11 = 'Widget9', #in12 = 'Widget10',
#in13 = 'Widget11', #in14 = 'Widget12', #in15 = 'Widget13', #in16 = 'Widget14',
#in17 = 'Widget15', #in18 = 'Widget16', #in19 = 'Widget17', #in20 = 'Widget18',
#in21 = 'DWidget19', #in22 = 'Widget20', #in23 = 'Widget21', #in24 = 'Widget22',
#in25 = 'Widget23', #in26 = 'Widget24', #in27 = 'Widget25', #in28 = 'Widget26',
#in29 = 'Widget27', #in30 = 'Widget28', #in31 = 'Widget29', #in32 = 'Widget30',
#in33 = 'Widget31', #in34 = 'Widget32', #in35 = 'Widget33', #in36 = 'Widget34',
#in37 = 'Widget35', #in38 = 'Widget36'
If you have to ask this question, you should probably use a temp table. Insert your parameters to the temp table and either JOIN your main table to it, or use an IN() predicate against a subquery of the temp table.
In most cases when you have 30+ parameters in an IN() predicate, you're going to find that you need more periodically. Using a temp table allows you to keep increasing the number of values without having to rewrite your query.
And it avoids any possibility of hitting a limit of the number of parameters or a limit on query length.

Resources