SQL - JOIN and SUBQUERY - sql

I'm trying to make a join in 2 tables (stg.ac_esb and stg.ac_eeb), both have emp_codigo, so im using this column to set the relation. But,when i try to extract the data from the join's result, the error says: ERROR: column reference "emp_codigo" is ambiguous. Can anyone help me with this plssss!
`SELECT
**emp_codigo** as NUMEMP /* Código da Empresa SIM*/
, epg_codigo as TIPCOL /* Tipo do Colaborador SIM*/
, ' ' as NUMCAD /* Cadastro do Colaborador SIM*/
, dtinicial as INIETB /* Data de Início da Estabilidade SIM */
, dtfinal as FIMETB /* Data Final da Estabilidade NÃO */
, codigo as CODETB /* Código da Estabilidade SIM */
FROM
(SELECT *
FROM stg.ac_esb
JOIN stg.ac_eeb
ON ac_esb.emp_codigo = ac_eeb.emp_codigo) AS Estabilidades;`

You can simplify your query ans qualify the emp_codigo column with the specific table where you want this value to come from. For example:
SELECT
ac_esb.emp_codigo as NUMEMP /* Código da Empresa SIM*/
, epg_codigo as TIPCOL /* Tipo do Colaborador SIM*/
, ' ' as NUMCAD /* Cadastro do Colaborador SIM*/
, dtinicial as INIETB /* Data de Início da Estabilidade SIM */
, dtfinal as FIMETB /* Data Final da Estabilidade NÃO */
, codigo as CODETB /* Código da Estabilidade SIM */
FROM stg.ac_esb
JOIN stg.ac_eeb
ON ac_esb.emp_codigo = ac_eeb.emp_codigo
Note: There may be more columns with duplicate names, so make sure you prepend each one with the table name where it belong to.

Related

Group by catid SQL result in a selectbox

I have a RSform (3.0.18) in Joommla (3.10.9) on server PHP (7.4.21).
One of the fields is a Dropdown (no multiselect) with a query SQL to get article from catid 15 OR 16. Thhe code below is given by RSForm documentation and adapted to my need.
//<code>
// Prepare the empty array
$items = array();
// Prepare the database connection
$db = JFactory::getDbo();
// Keep this if you'd like a "Please select" option, otherwise comment or remove it
$items[] = "|Sélectionnez...[c]";
// Run the SQL query and store it in $results
$db->setQuery("SELECT id, title FROM #__content WHERE catid = 15 or catid = 16");
$results = $db->loadObjectList();
// Now, we need to convert the results into a readable RSForm! Pro format.
// The Items field will accept values in this format:
// value-to-be-stored|value-to-be-shown
// Eg. m|M-sized T-shirt
foreach ($results as $result) {
$value = $result->id;
$label = $result->title;
$items[] = $value.'|'.$label;
}
// Multiple values are separated by new lines, so we need to do this now
$items = implode("\n", $items);
// Now we need to return the value to the field
return $items;
//</code>
The query works and I get a result like :
Sélectionnez...
Introduction aux médias et à la prise de parole en public
Réussir une prise de parole
Réussir une interview
Médiatraining élus
But I would like it group by catid, which could give something like :
Sélectionnez...
Enterprises formations (not selectable)
Introduction aux médias et à la prise de parole en public
Réussir une prise de parole
Réussir une interview
Administrations formations (not selectable)
Médiatraining élus
Any advice to help writing this ?
Thanks in advance...

add columns in a CDS view and fill it with a condition

I have been trying for several days, in a cds view, to convert a row of the acdoca table (here the amount of a debit/credit transaction, the hsl attribute in acdoca), into two columns debit and credit.
The amount of a transaction would go into a column depending on the type of debit/credit (attribute drcrk in acdoca which returns H for a debit or S for a credit). Is there a solution to my problem or a doc accessible to a beginner to solve this problem
(PS I don't know ABAP so if you have a solution using it is it possible to describe where and how to integrate it to Eclipse).
I tried to declare a direct attribute in the view, to alter the view, but all this does not work. I have been told about the possibility of using a functional table, which seems to work, but I can't structure it correctly just in the typing of my tables.
I can pass my view if necessary.
define view Z_test_dc as select from acdoca
inner join bseg on acdoca.rbukrs = bseg.bukrs
and bseg.belnr = acdoca.belnr
and bseg.gjahr = acdoca.gjahr
and bseg.buzei = acdoca.buzei
left outer join but000 on but000.partner = acdoca.kunnr
left outer join t003t on t003t.blart = acdoca.blart
{
key acdoca.rbukrs, //Société
key acdoca.gjahr, //Exercice comptable
key acdoca.belnr, //Numéro de pièce comptable
key acdoca.racct, //Numéro de compte
key acdoca.docln, //Ligne d'écriture à six caractères pour ledger
acdoca.kunnr, //Client
acdoca.fiscyearper, //Période/exercice
acdoca.augbl, //Nº pièce rapprochement
acdoca.bldat, //Date de la pièce
acdoca.budat, //Date comptable du document
acdoca.blart, //Type de pièce
t003t.ltext, //Description type de pièce
acdoca.hsl, //Montant en devise société
acdoca.rhcur, //Devise société
acdoca.netdt, //Date echéance nette
bseg.madat, //Data de la dernière relance
bseg.mansp, //Blocage relance
bseg.manst, //Niveau de relance
bseg.zterm, //Conditions de paiement
but000.bu_group, //le regroupement du client
bseg.valut, //Date valeur delais
bseg.sgtxt, //Texte descriptif postes
acdoca.drcrk //type debit/credit (return H ou S)
}
...
I didn't think it was possible, because I had thought that an alias as just a renamed of my column, but with the right syntax the box works fine here is the code I rendered thanks for your help.
define view VIEW as select from acdoca
inner join bseg on acdoca.rbukrs = bseg.bukrs
and bseg.belnr = acdoca.belnr
and bseg.gjahr = acdoca.gjahr
and bseg.buzei = acdoca.buzei
left outer join but000 on but000.partner = acdoca.kunnr
left outer join t003t on t003t.blart = acdoca.blart {
key acdoca.rbukrs, //Société
key acdoca.gjahr, //Exercice comptable
key acdoca.belnr, //Numéro de pièce comptable
key acdoca.racct, //Numéro de compte
key acdoca.docln, //Ligne d'écriture à six caractères pour ledger
acdoca.kunnr, //Client
acdoca.fiscyearper, //Période/exercice
acdoca.augbl, //Nº pièce rapprochement
acdoca.bldat, //Date de la pièce
acdoca.budat, //Date comptable du document
acdoca.blart, //Type de pièce
t003t.ltext, //Description type de pièce
acdoca.hsl, //Montant en devise société
acdoca.rhcur, //Devise société
acdoca.netdt, //Date echéance nette
bseg.madat, //Data de la dernière relance
bseg.mansp, //Blocage relance
bseg.manst, //Niveau de relance
bseg.zterm, //Conditions de paiement
but000.bu_group, //le regroupement du client
bseg.valut, //Date valeur delais
bseg.sgtxt, //Texte descriptif postes
acdoca.drcrk, //type debit/credit (return H ou S)
case acdoca.drcrk when 'H' then acdoca.hsl else 0 end as debit,
case acdoca.drcrk when 'S' then acdoca.hsl else 0 end as credit
}'

Symfony createQuery winth multiple table

I would like to recover the user who wrote the post, only I have an error when I try to do it "Attempted to call an undefined method named "getIdPost" of class "App\Entity\User"."
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery( //creation de la requête
'SELECT p , u
FROM App\Entity\User u, App\Entity\Post p
WHERE p.Id_Post_Parent IS NULL
AND p.Id_User = u.idUser
ORDER BY p.Post_Date_Time DESC'
)->setMaxResults(10);
$posts = $query->getResult();
$publicPosts = array();
$comments = array();
for($i = 0; $i<sizeof($posts) ; $i++){
$publicPosts[$i] = $posts[$i]->getArray();
//récupération des commentaires
$em = $this->getDoctrine()->getManager(); //on appelle Doctrine
$query = $em->createQuery( //creation de la requête
'SELECT p , u
FROM App\Entity\User u, App\Entity\Post p
WHERE p.Id_Post_Parent = :idParent
AND p.Id_User = u.idUser'
)->setParameter('idParent', $posts[$i]->getIdPost())
->setMaxResults(10); //On limite à 10 commentaires par posts
$comments[$i] = $query->getResult(); //variable qui récupère la requête
}
If I remove the User entity of the query it works and I have no error ... I do not understand what it's due, why it tells me that there is no method "getIdPost" in user? This is normal since it is a method of "Post" :x
you would like the user who wrote the post it's a bit weird to get it from a query don't you have a $post->getUser() ? I think you should join the table to acheive that
$query = $em->createQuery( //creation de la requête
'SELECT u
FROM App\Entity\User u,
LEFT JOIN App\Entity\Post p on p.Id_User = u.idUser
WHERE p.Id_Post_Parent IS NULL
ORDER BY p.Post_Date_Time DESC'
)->setMaxResults(10);

SQL • Result of join in an array

Good evening,
Here is my problem: I make a select query on my table PROJECT to select (for now) my only test project. I do a join on the table to retrieve screenshots SCREENSHOT associated with it. Only he will get out as many results as there are screenshots! Ie here 5.
Could I go back to more data (name, datesortie, description, etc.) an associative array urls screenshots?
Or would you have a solution to simplify my life? Because the only solution I see is treating it directly in php.
Here is my query:
SELECT P.nom, datesortie, description, lien, icone, tag, S.url
FROM PROJET P
LEFT JOIN CLIENT C
ON C.idclient = P.idclient
LEFT JOIN SCREENSHOT S
ON S.idprojet = P.idprojet
ORDER BY P.nom
Here is what is returned (Sorry, my var_dump shows me that online ... I do not understand why):
array(7) { ["nom"]=> string(10) "BlackStars" ["datesortie"]=> string(10) "2012-07-02" ["description"]=> string(498) "Inspiré par Little Stars for Little Wars, Black Stars se veut être meilleur par bien des aspects. Prenez le contrôle d'une planète et partez à la conquête de l'univers en remportant chacune des batailles, en brisant chacune des planètes ennemies, en devenant le meilleur joueur. Car une fois le mode solo terminé, un mode multi-joueurs (Bluetooth ou Game Center) vous attend afin de vous mesurer au monde entier. Hissez-vous en haut du classement et devenez le maître incontesté de Black Stars. " ["lien"]=> string(69) "http://itunes.apple.com/us/app/black-stars/id512945753?l=fr&ls=1&mt=8" ["icone"]=> string(131) "http://a1775.phobos.apple.com/us/r30/Purple/v4/73/47/b7/7347b764-cff9-c52b-78da-42560a187acf/mza_1097997557772736292.170x170-75.png" ["tag"]=> string(10) "blackstars" ["url"]=> string(119) "http://a1352.phobos.apple.com/us/r30/Purple/v4/51/df/f5/51dff56b-08c6-59db-81df-80a174ec0050/mza_509496145749890361.png" }
===================================================
===================================================
array(7) { ["nom"]=> string(10) "BlackStars" ["datesortie"]=> string(10) "2012-07-02" ["description"]=> string(498) "Inspiré par Little Stars for Little Wars, Black Stars se veut être meilleur par bien des aspects. Prenez le contrôle d'une planète et partez à la conquête de l'univers en remportant chacune des batailles, en brisant chacune des planètes ennemies, en devenant le meilleur joueur. Car une fois le mode solo terminé, un mode multi-joueurs (Bluetooth ou Game Center) vous attend afin de vous mesurer au monde entier. Hissez-vous en haut du classement et devenez le maître incontesté de Black Stars. " ["lien"]=> string(69) "http://itunes.apple.com/us/app/black-stars/id512945753?l=fr&ls=1&mt=8" ["icone"]=> string(131) "http://a1775.phobos.apple.com/us/r30/Purple/v4/73/47/b7/7347b764-cff9-c52b-78da-42560a187acf/mza_1097997557772736292.170x170-75.png" ["tag"]=> string(10) "blackstars" ["url"]=> string(119) "http://a572.phobos.apple.com/us/r30/Purple/v4/db/1d/1d/db1d1d00-3a28-8b6f-d52f-342bf5893912/mza_3642427234916705950.png" }
===================================================
===================================================
array(7) { ["nom"]=> string(10) "BlackStars" ["datesortie"]=> string(10) "2012-07-02" ["description"]=> string(498) "Inspiré par Little Stars for Little Wars, Black Stars se veut être meilleur par bien des aspects. Prenez le contrôle d'une planète et partez à la conquête de l'univers en remportant chacune des batailles, en brisant chacune des planètes ennemies, en devenant le meilleur joueur. Car une fois le mode solo terminé, un mode multi-joueurs (Bluetooth ou Game Center) vous attend afin de vous mesurer au monde entier. Hissez-vous en haut du classement et devenez le maître incontesté de Black Stars. " ["lien"]=> string(69) "http://itunes.apple.com/us/app/black-stars/id512945753?l=fr&ls=1&mt=8" ["icone"]=> string(131) "http://a1775.phobos.apple.com/us/r30/Purple/v4/73/47/b7/7347b764-cff9-c52b-78da-42560a187acf/mza_1097997557772736292.170x170-75.png" ["tag"]=> string(10) "blackstars" ["url"]=> string(120) "http://a1701.phobos.apple.com/us/r30/Purple/v4/60/5f/ae/605fae3e-f00b-c3b7-0f65-ca73f6fd9864/mza_4565911160744621776.png" }
===================================================
===================================================
array(7) { ["nom"]=> string(10) "BlackStars" ["datesortie"]=> string(10) "2012-07-02" ["description"]=> string(498) "Inspiré par Little Stars for Little Wars, Black Stars se veut être meilleur par bien des aspects. Prenez le contrôle d'une planète et partez à la conquête de l'univers en remportant chacune des batailles, en brisant chacune des planètes ennemies, en devenant le meilleur joueur. Car une fois le mode solo terminé, un mode multi-joueurs (Bluetooth ou Game Center) vous attend afin de vous mesurer au monde entier. Hissez-vous en haut du classement et devenez le maître incontesté de Black Stars. " ["lien"]=> string(69) "http://itunes.apple.com/us/app/black-stars/id512945753?l=fr&ls=1&mt=8" ["icone"]=> string(131) "http://a1775.phobos.apple.com/us/r30/Purple/v4/73/47/b7/7347b764-cff9-c52b-78da-42560a187acf/mza_1097997557772736292.170x170-75.png" ["tag"]=> string(10) "blackstars" ["url"]=> string(119) "http://a193.phobos.apple.com/us/r30/Purple/v4/7c/ff/67/7cff67dc-d679-16ee-24cf-7f658c78b9c8/mza_8709328453215958742.png" }
===================================================
===================================================
array(7) { ["nom"]=> string(10) "BlackStars" ["datesortie"]=> string(10) "2012-07-02" ["description"]=> string(498) "Inspiré par Little Stars for Little Wars, Black Stars se veut être meilleur par bien des aspects. Prenez le contrôle d'une planète et partez à la conquête de l'univers en remportant chacune des batailles, en brisant chacune des planètes ennemies, en devenant le meilleur joueur. Car une fois le mode solo terminé, un mode multi-joueurs (Bluetooth ou Game Center) vous attend afin de vous mesurer au monde entier. Hissez-vous en haut du classement et devenez le maître incontesté de Black Stars. " ["lien"]=> string(69) "http://itunes.apple.com/us/app/black-stars/id512945753?l=fr&ls=1&mt=8" ["icone"]=> string(131) "http://a1775.phobos.apple.com/us/r30/Purple/v4/73/47/b7/7347b764-cff9-c52b-78da-42560a187acf/mza_1097997557772736292.170x170-75.png" ["tag"]=> string(10) "blackstars" ["url"]=> string(120) "http://a1443.phobos.apple.com/us/r30/Purple/v4/d7/13/8f/d7138f62-6398-7993-8d0b-23e0ce16dca2/mza_8316005873463209973.png" }
===================================================
===================================================
Thank you in advance for your help.
Cordially.
From what I gather, you just don't want all that repeating information in the first 6 fields?
Normally, accepting the repeating information is the way to go about it. But, you could pull back two record sets. Provided that they're neatly ordered you can do a nested loop to process them.
SELECT P.nom, datesortie, description, lien, icone, tag, idproject
FROM PROJET P
LEFT JOIN CLIENT C
ON C.idclient = P.idclient
LEFT JOIN SCREENSHOT S
ON S.idprojet = P.idprojet
ORDER BY P.nom
SELECT P.idproject S.url
FROM PROJET P
INNER JOIN SCREENSHOT S
ON S.idprojet = P.idprojet
ORDER BY P.nom
Note: The first query now also has the idproject field, which is also present in the second record set. The second record set is also ordered by P.nom, even though it's not selected in the statement; this just ensures that you can do a simple nested loop.
A simplifies pseudo-code could be...
FOR EACH nom IN recordSet1
WHILE recordSet1.idProject = recordSet2.idProject
Do something with the URL
Move to next record in recordSet2
LOOP
LOOP
What I would not do
Another option is to concatenate all of the URLs together into a single string. Perhaps separated by commas to make a CSV field.
But then the existence of a comma in the url will break that. So you probably then want to use XML or something; with added costs to generate and parse.
Unless the network overhead of the repeated fields is actually causing a problem, I would stick to that. And if it is causing a problem, the two-record-set alternative is more robust and relatively simple.

Converting HQL Query to Criteria generates invalid SQL

I am attempting to convert the following HQL query to Criteria.
from SubportfolioAudit as a
where a.ID in (select max(a2.ID)
from SubportfolioAudit as a2
where a2.EffectiveDate = :EffectiveDate
and a.Subportfolio.ID = a2.Subportfolio.ID
group by a2.Subportfolio.ID)
and a.Subportfolio.ID in (:SubportfolioList)
So far I have the following:
var crit = Session.CreateCriteria(typeof(SubportfolioAudit));
var currentAuditByEffectiveDate = DetachedCriteria.For(typeof(SubportfolioAudit))
.SetProjection(Projections.ProjectionList()
.Add(Projections.Max("ID"))
.Add(Projections.GroupProperty("Subportfolio.ID")))
.Add(Expression.Eq("EffectiveDate", effectiveDate));
crit.Add(Subqueries.PropertyIn("ID", currentAuditByEffectiveDate));
crit.Add(Expression.In("Subportfolio.ID", subportfolioList.Select(x => x.ID).ToArray()));
return crit.List<SubportfolioAudit>();
Which generates an invalid sub query, you can see it here:
SELECT this_.SubportfolioAuditId as Subportf1_21_6_,
this_.Event as Event21_6_,
this_.CreatedDate as CreatedD3_21_6_,
this_.[User] as User4_21_6_,
this_.EffectiveDate as Effectiv5_21_6_,
this_.SubportfolioId as Subportf6_21_6_,
subportfol2_.SubportfolioId as Subportf1_12_0_,
subportfol2_.PACERCode as PACERCode12_0_,
subportfol2_.HedgeRatio as HedgeRatio12_0_,
subportfol2_.Name as Name12_0_,
subportfol2_.Strategy as Strategy12_0_,
subportfol2_.BasketId as BasketId12_0_,
subportfol2_.PortfolioId as Portfoli7_12_0_,
subportfol2_.ReferenceBasketId as Referenc8_12_0_,
(SELECT CASE
WHEN Count(* ) > 0
THEN 1
ELSE 0
END
FROM Asset
WHERE Asset.SubportfolioId = subportfol2_.SubportfolioId) as formula1_0_,
basket3_.BasketId as BasketId7_1_,
basket3_.Name as Name7_1_,
basket3_.CatsBenchmarkCode as CatsBenc4_7_1_,
basket3_.Description as Descript5_7_1_,
basket3_.BaseBasketId as BaseBask6_7_1_,
basket3_.Filename as Filename7_1_,
basket3_.Type as Type7_1_,
basket4_.BasketId as BasketId7_2_,
basket4_.Name as Name7_2_,
basket4_.CatsBenchmarkCode as CatsBenc4_7_2_,
basket4_.Description as Descript5_7_2_,
basket4_.BaseBasketId as BaseBask6_7_2_,
basket4_.Filename as Filename7_2_,
basket4_.Type as Type7_2_,
portfolio5_.PortfolioId as Portfoli1_5_3_,
portfolio5_.BaseCurrencyCode as BaseCurr2_5_3_,
portfolio5_.TradingAccountNumber as TradingA3_5_3_,
portfolio5_.Name as Name5_3_,
portfolio5_.ClientId as ClientId5_3_,
client6_.ClientId as ClientId4_4_,
client6_.ExplicitFee as Explicit2_4_4_,
client6_.Affiliated as Affiliated4_4_,
client6_.ClientGroup as ClientGr4_4_4_,
client6_.RCODA as RCODA4_4_,
client6_.Name as Name4_4_,
client6_.BaseCurrencyCode as BaseCurr7_4_4_,
client6_.Region as Region4_4_,
basket7_.BasketId as BasketId7_5_,
basket7_.Name as Name7_5_,
basket7_.CatsBenchmarkCode as CatsBenc4_7_5_,
basket7_.Description as Descript5_7_5_,
basket7_.BaseBasketId as BaseBask6_7_5_,
basket7_.Filename as Filename7_5_,
basket7_.Type as Type7_5_
FROM dbo.SubportfolioAudit this_
inner join dbo.Subportfolio subportfol2_
on this_.SubportfolioId = subportfol2_.SubportfolioId
left outer join dbo.Basket basket3_
on subportfol2_.BasketId = basket3_.BasketId
left outer join dbo.Basket basket4_
on basket3_.BaseBasketId = basket4_.BasketId
left outer join dbo.Portfolio portfolio5_
on subportfol2_.PortfolioId = portfolio5_.PortfolioId
left outer join dbo.Client client6_
on portfolio5_.ClientId = client6_.ClientId
left outer join dbo.Basket basket7_
on subportfol2_.ReferenceBasketId = basket7_.BasketId
WHERE this_.SubportfolioAuditId in (SELECT max(this_0_.SubportfolioAuditId) as y0_,
this_0_.SubportfolioId as y1_
FROM dbo.SubportfolioAudit this_0_
WHERE this_0_.EffectiveDate = '2009-09-11T00:00:00.00' /* #p0 */
GROUP BY this_0_.SubportfolioId)
and this_.SubportfolioId in (13 /* #p1 */,14 /* #p2 */,15 /* #p3 */,16 /* #p4 */,
17 /* #p5 */,18 /* #p6 */,19 /* #p7 */,20 /* #p8 */,
21 /* #p9 */)
I know that the Projections.GroupProperty() is causing the problem, but I cannot seem to find another way to accomplish what I want.
I believe (and correct me if I am wrong) that the sub query is invalid because you are missing the second where clause you have set in your HQL (... and a.Subportfolio.ID = a2.Subportfolio.ID).
Converting your Criteria query as below I believe (cannot verify as I cannot test your code) that it will do the trick.
var crit = Session.CreateCriteria(typeof(SubportfolioAudit), "mainQuery");
var currentAuditByEffectiveDate = DetachedCriteria.For(typeof(SubportfolioAudit),"subQuery")
.SetProjection(Projections.ProjectionList()
.Add(Projections.Max("ID"))
.Add(Projections.GroupProperty("Subportfolio.ID")))
.Add(Expression.Eq("EffectiveDate", effectiveDate));
.Add(Expression.EqProperty("subQuery.ID", "mainQuery.ID"));
crit.Add(Subqueries.PropertyIn("mainQuery.ID", currentAuditByEffectiveDate));
crit.Add(Expression.In("mainQuery.Subportfolio.ID", subportfolioList.Select(x => x.ID).ToArray()));
return crit.List<SubportfolioAudit>();
What I have done is to add an extra where clause in the DetachedCriteria that 'connects' the SubportfoliAudit.ID column of the subquery with the outer main query. I have also provided aliases to name the queries.