SQL Server substring(substring()) - sql-server

Using two times the substing() is giving me an error.
Is there a way to get the same result ?
select [Identifiant] as [ID payment],
[Etat de la dépense] as [Status payment],
[Code bénéficiaire] as [Recipient code of payment],
substring(substring([Information projet], 83, 100) as [sting], 1, PATINDEX('%Code Branche%', [string])-1) as [Recipient of payment]
into [DB].[dbo].[Check_Result]
from [DB].[dbo].Expenses_SAP$

You can't alias the inner substring. It's unclear what you would try to achieve by doing this, so I can't really suggest the correct way to do whatever it is.
Take out as [sting] and at least you should have valid syntax:
substring(substring([Information projet], 83, 100), 1, PATINDEX('%Code Branche%', [string])-1) as [Recipient of payment]

I have a feeling that you're trying to do something like the following...
SELECT
es.Identifiant as [ID payment],
es.[Etat de la dépense] as [Status payment],
es.[Code bénéficiaire] as [Recipient code of payment],
substring(ss.sub_string, 1, PATINDEX('%Code Branche%', ss.sub_string)-1) as [Recipient of payment]
into [DB].[dbo].[Check_Result]
FROM
DB.dbo.Expenses_SAP es
CROSS APPLY ( VALUES (substring([Information projet], 83, 100)) ) ss (sub_string);

Related

CakePHP: How to Code in Cakephp 4 with Multiple LEFT JOINS Where One LEFT JOIN Is Not Associated to the Main Table

OBJECTIVE:
DISPLAY A LIST OF:
MEMBER ID/ MEMBER NAME/ DATE VISITED/ MEMBER'S GRADE
This is the SQL statement I want to code in CakePHP 4:
SELECT visits.member_id, members.mbr_name, visits.created, batches.grade_id
FROM visits
LEFT JOIN members ON members.mbrid = visits.member_id
LEFT JOIN batches ON batches.member_id = members.mbrid
WHERE batches.batch = '2020' AND (batches.sub_batch = '0' OR batches.sub_batch = '1')
ORDER BY visits.created DESC
As you can see, the second LEFT JOIN clause is only related to members, instead of the main table visits.
This is the way I code it in CakePHP 4:
$this->Visits->find()
->contain('Members.Batches', function (Query $q) {
return $q
->select('member_id', 'batch', 'sub_batch', 'grade_id')
->where(['Batches.batch' => '2020', 'Batches.sub_batch' => '0']);
})
->contain('Members')
->order(['Visits.created' => 'DESC'])
);
In the Debug mode, I can see two(2) SQL generated. Not what I expected:
SELECT
Visits.id AS Visits__id,
Visits.member_id AS Visits__member_id,
Visits.vst_datetime AS Visits__vst_datetime,
Visits.location_id AS Visits__location_id,
Visits.created AS Visits__created,
Visits.modified AS Visits__modified,
Members.id AS Members__id,
Members.mbrid AS Members__mbrid,
Members.mbr_name AS Members__mbr_name,
Members.mbr_type AS Members__mbr_type,
Members.created AS Members__created,
Members.modified AS Members__modified
FROM
visits Visits
LEFT JOIN members Members ON Members.mbrid = (Visits.member_id)
ORDER BY
Visits.created DESC
LIMIT
20 OFFSET 0
SELECT
Batches.member_id AS Batches__member_id
FROM
batches Batches
WHERE
(
Batches.member_id in (
187, 1471, 1470, 1463, 250, 350, 1000,
501, 300, 255, 254, 253, 3, 303, 215,
305, 202, 201
)
AND Batches.batch = '2020'
AND Batches.sub_batch = '0'
)
Here's the code that gives me the sql that I need:
$visits = $this->Paginator->paginate($this->Visits->find()
->select(['Members.mbrid', 'Members.mbr_name', 'Visits.created', 'Batches.grade_id'])
->leftJoinWith('Members')
->leftJoinWith('Members.Batches')
->where(['Batches.batch' => '2020', 'Batches.sub_batch' => '0'])
->order(['Visits.created' => 'DESC'])
);
As suggested by #ndm by using leftJoinWith.

How do debug "object is not subscriptable" in Python?

It seems like I can't do this:
user=csv_reader[0 + row_count]
This code is for a university project and I'm running it on repl.it. If you want to take a look, it's posted here: https://repl.it/#Lia_AlexaAlexa/ConsciousYummySeahorse
import csv
def comprobando_usuario(usuario_var):
csv_reader = open("ale.csv")
row_count = len(csv_reader.readlines())
while row_count >= 1:
user=csv_reader[0 + row_count]
useri=user[1]
while usuario_var in useri:
usuario_var=str(("Ingrese nuevo usuario o escribe no para
terminar."))
row_count=row_count - 1
if usuario_var in abc:
return(0)
return(100)
Error:
Traceback (most recent call last):
File "main.py", line 14, in <module>
respuesta_de_usuario= usuario.comprobando_usuario(usuario_var)
File "/home/runner/usuario.py", line 6, in comprobando_usuario
user=csv_reader[0 + row_count]
TypeError: '_io.TextIOWrapper' object is not subscriptable
Indeed, you can't do user=csv_reader[0 + row_count] as csv_reader is a file object that you created from csv_reader = open("ale.csv").
Also, you should get rid of this complex while loop and follow the doc to know how to read a file properly in Python: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

character(0) get the first table but canot get to second table on pae

Trying to webscrape from HTML.
Using Inspector gadget.
No problems with the 1st table on page. With 2nd table, Iget character(0) or Nodeset(0)
library(rvest)
library(plyr)
date1=20161011
gdf1 <- data.frame(matrix(0, ncol = 11, nrow = 1))
newdate<-date1
# HOCKEY
year<-2015
# date1=newdate[d]
date1=2010
#for (yr in 1:10){
date1=date1+1
c<-paste("https://www.hockey-reference.com/leagues/NHL_",date1,".html",sep="")
nbc<-read_html(c)
nbc
#tables<-html_nodes(nbc,".center , #games , .right:nth-child(5), .right:nth-child(3), #games a")
tables<-html_nodes(nbc,"#stats .right , #stats a")
g<-html_text(tables)

Extracting text from big files in Prolog

I would like to extract text between a start and end string with SWI-Prolog, e.g., all the titles from Wikipedia dumps. I don't want to use an XML-parser, as I want to deal with different file types in the same way. I got it working for small files, but run into problems for large files.
For big files (e.g., Romanian Wikipedia) prolog runs out of memory (prolog -G1G -L1G -T1G -s main.pl -t main, see content of main.pl below):
Welcome to SWI-Prolog (threaded, 64 bits, version 7.4.2)
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.
Please run ?- license. for legal details.
For online help and background, visit http://www.swi-prolog.org
For built-in help, use ?- help(Topic). or ?- apropos(Word).
found: 'Rocarta'
found: 'Muzică'
found: 'Iris (formație românească)'
found: 'Pagina principală'
...[removed hundreds of lines]
found: 'Zadar'
found: 'Australia'
found: 'Slovenia'
found: 'Croația'
ERROR: Out of global stack
Exception: (5,861) between([60, 116, 105, 116, 108, 101, 62], [60, 47, 116, 105, 116, 108, 101, 62], _264890370, [10, 32, 32, 32, 32, 60, 110, 115|...], []) ?
How to accomplish this task with big input files?
MWE (main.pl):
:- use_module(library(pio)).
:- use_module(library(dcg/basics)).
last_call_optimisation(true).
main :-
phrase_from_file(between(`<title>`, `</title>`, _), `wiki.xml`).
between(Start, End, Found) -->
string(_), string(Start), string(Found), string(End),
{ format("found: '~s' \n", [Found]) },
between(Start, End, _).
between(_, _, []) -->
remainder(_),
{ format("finished parsing") }.
example input (wiki.xml):
<mediawiki>
>< Don't use an XML parser! ><
<page><title>Albert Einstein</title></page>
<page><title>Elvis Presley</title></page>
</mediawiki>
example output (expected):
found: 'Albert Einstein'
found: 'Elvis Presley'
finished parsing
Edit:
If we remove the recursive call from between/3, the output changes, and doesn't correspond to what I expect:
found: 'Albert Einstein'
found: 'Albert Einstein</title></page>
<page><title>Elvis Presley'
found: 'Elvis Presley'
finished parsing
this construct
..., string(_), string(Start), ...
it's very inefficient. It turns a linear parse into an exponential one.
But we have a really simple solution, since a string literal performs an exact match in a DCG:
:- use_module(library(dcg/basics)).
main(Titles) :-
%phrase_from_file(between(`<title>`, `</title>`, Titles),`wiki.xml`).
phrase(between(`<title>`, `</title>`, Titles), `
<mediawiki>
>< Don't use an XML parser! ><
<page><title>Albert Einstein</title></page>
<page><title>Elvis Presley</title></page>
</mediawiki>
`).
between(_Start, _End, []) --> [].
between(Start, End, [Found|Rest]) -->
Start, string(String), End,
{ atom_codes(Found, String) },
!, between(Start, End, Rest).
between(Start, End, List) --> [_], between(Start, End, List).
I would simplify the code, though:
...
phrase(tag(`title`, Titles), `
...
tag(_Tag, []) --> [].
tag(Tag, [Found|Rest]) -->
"<", Tag, ">", string(String), "</", Tag, ">",
{ atom_codes(Found, String) },
!, tag(Tag, Rest).
tag(Tag, List) --> [_], tag(Tag, List).
My bet is that on large files this is slightly more efficient.
It's also easy to generalize:
...
phrase(tags([title, footnote], Contents), `
...
tags(_Tags, []) --> [].
tags(Tags, [Key-Found|Rest]) -->
"<", {member(Tag, Tags)}, Tag, ">", string(String), "</", Tag, ">",
{ maplist(atom_codes, [Found,Key], [String,Tag]) },
!, tags(Tags, Rest).
tags(Tags, List) --> [_], tags(Tags, List).
but not very efficient. Better (but should profile to prove it)
...
"<", string(Tag), ">", {memberchk(Tag, Tags)}, string(String), "</", Tag, ">",
...
Edit: at least on a small set of Tags, "<", {member(Tag, Tags)}, Tag, ">" seems to require a lot less inferences than "<", string(Tag), ">", {memberchk(Tag, Tags)},.

SPARQL using union with a dataset

The challenge set is to use the UNION keyword with the following datasets and return a list of grandads.
RELDB1 holds 2 useful tables:
The fatherOf table has this data:
Table fatherof:
('Chuck', 'Paul'),
('Chuck', 'Bonnie'),
('Jerry', 'George'),
('Jerry', 'Mary'),
('Chuck', 'Olivia'),
('Paul', 'Joan'),
('George', 'John'),
('George', 'Carole'),
('Ringo', 'Yoko'),
('Ringo', 'Peter')
and the table Person has:
Table person:
('Sara', 64, 'f'),
('Nancy', 68, 'f'),
('Mary', 27, 'f'),
('Olivia', 37, 'f'),
('Bonnie', 35, 'f'),
('Carole', 7, 'f'),
('Yoko', 6, 'f'),
('Joan', 9, 'f'),
('Chuck', 67, 'm'),
('Jerry', 65, 'm'),
('Paul', 30, 'm'),
('George', 25, 'm'),
('Ringo', 39, 'm'),
('John', 8, 'm'),
('Peter', 11, 'm')
I tried this query:
>SELECT ?x ?y ?z
>WHERE {{?x rdf:type ex:Person}
>UNION
>{?x ex:fatherOf ?y . ?y ex:fatherOf ?z}}
>ORDER BY (?x)
The output was everyone in the Person table and then also the son and grandchild for Chuck (Paul, Joan) and Jerry (George, John and George and Carole). I tried removing ?y ?z. The query returned a list of the person table!
How can I modify the query so that the UNION remains but I get only grandparents. Any guidance would be appreciated.
You are trying to return every person who is a grandfather. In your question you show that you are only returning paternal grandparents...
A grandfather has children who has children who has children.
Grandfather
Son Daughter
Son Daughter Son Daughter
The union part come into play because you are going to return the following:
?z father of ?a
?a mother of ?b
?a father of ?b
?z
?a ?a
?b ?b ?b ?b
You need a union on the mother and father of ?b as you are combining the results of multiple triple patterns. I won't provide you with the query for this as this is classwork, however, this should help you arrive at the answer using what you have.

Resources