T-SQL 2 or more Joins on same table - tsql

im trying to do two left joins on the same table but it won't work and i have no idea why...
Can someone help me with that?
Thats my code:
CREATE VIEW [dbo].[Sportwetten_Data]
AS
SELECT TOP 1000 Main.id AS id,
Main.date AS date,
Concat(Main.hometeam, ' - ', Main.awayteam) AS event,
Concat(Goals.homescored, '/', Goals.homeconceded, ' - ',
Goals.awayscored, '/',
Goals.awayconceded) AS goals,
LB.bet AS bet,
Main.entry AS entry,
Main.odd AS odd,
Concat(Result.homegoals, ':', Result.awaygoals) AS result,
LS.type AS status
FROM Main,
Goals,
Result,
Main AS M
LEFT JOIN Lookup_Bettype LB
ON M.bettype = LB.bettype
LEFT JOIN Lookup_Status LS
ON M.status = LS.type
WHERE Main.id = Goals.id
ORDER BY Main.id ASC
Everything works fine, except for the
LEFT JOIN Lookup_Status LS
ON M.status = LS.type
And of course
LS.type AS status

I had the same problema couple of month ago with a query with joins like yours:
FROM Main,
Goals,
Result,
Main AS M
Try to explicit the join between those tables. worked for me

Related

Is there a way to modify this query and make it more simple?

I am working on a MySQl data base and have several tables that I need to join based on a temporary table that I created (layer_2).
Each table that I join has the join key for the next table;
E.g. layer_2 joins with "colegios" table, then the result will have the join key for the next table "ciudades". and finally the result will have the Join key for the next table "departamentos".
from what I got it works but I want to know if there is a way to simplify this?
Select
cuestionario_id,
tiempo,
nro_preguntas,
nro_preguntas_correctas,
tipo_usuario,
fecha_creacion_cuestionario,
con_tiempo,
det_cuestionarios_id,
respuesta_seleccionada,
pregunta_id,
enunciado,
respuesta_correcta,
usuarios_id,
dominio_correo,
tipo_institucion,
materia,
tematica,
area,
nombre_colegios,
direccion_colegios,
nombre_ciudades,
redsaber.departamentos.nombre as nombre_departamentos
From
(
Select
cuestionario_id,
tiempo,
nro_preguntas,
nro_preguntas_correctas,
cuestionable_id,
tipo_usuario,
fecha_creacion_cuestionario,
con_tiempo,
det_cuestionarios_id,
respuesta_seleccionada,
pregunta_id,
enunciado,
respuesta_correcta,
usuarios_id,
dominio_correo,
cole_ciud_id,
tipo_institucion,
materia,
tematica,
area,
combine_ciudad_id,
nombre_colegios,
direccion_colegios,
redsaber.ciudades.nombre as nombre_ciudades,
departamento_id
From
(Select
cuestionario_id,
tiempo,
nro_preguntas,
nro_preguntas_correctas,
cuestionable_id,
tipo_usuario,
fecha_creacion_cuestionario,
con_tiempo,
det_cuestionarios_id,
respuesta_seleccionada,
pregunta_id,
enunciado,
respuesta_correcta,
usuarios_id,
dominio_correo,
cole_ciud_id,
tipo_institucion,
materia,
tematica,
area,
ifnull(redsaber.colegios.ciudad_id,cole_ciud_id) as combine_ciudad_id,
redsaber.colegios.nombre as nombre_colegios,
redsaber.colegios.direccion as direccion_colegios
From layer_2
Left Join redsaber.colegios on layer_2.cole_ciud_id = redsaber.colegios.id
AND tipo_institucion = 'Colegio') as layer_3
Left Join redsaber.ciudades on combine_ciudad_id = redsaber.ciudades.id) as layer_4
Left Join redsaber.departamentos on departamento_id = redsaber.departamentos.id

too many column names were specified

how can i deal with that error?
ERROR: too many column names were specified
i can't figure out what i have to change to make this work.
Is there really too many columns in my CREATE statement or is this in the AS SELECT that goes wrong?
CREATE TABLE planification_finale_asset2_test
( nom,
nom_court,
serveur,
scheduled_backup,
schedule,
retention,
groupe,
remote_access,
alias,
parallelisme,
storage_nodes,
client_OS_type,
version_networker,
savesets,
ALIAS_1,
ALIAS_2,
APPLICATION,
ENVIRONNEMENT,
environnement_global,
IMPACT,
CLIENT_OPERATIONNEL,
TYPE,
SITE,
COMPOSANT_DE,
COMPOSE_DE ,
ETAT,
POIDS,
EQUIPE_EXPLOITATION,
debut_sauvegarde,
groupe_actif,
intervalle,
clones,
retention_policy,
calendrier,
commentaire,
volume_sauvegarde,
volume_externalise,
volume_replique,
"3P2I") AS
SELECT t1.*, CONCAT(groupe, ' status ', scheduled_backup) AS etat_groupe,
CONCAT(groupe, ' status ', groupe_actif) AS etat_groupe_actif,
t3.volume_sauvegarde, t3.volume_externalise, t3.volume_replique
from planification_client_biens_group_test t1
LEFT OUTER JOIN volumetrie_1_jour t3
ON t1.nom LIKE CONCAT(t3.client, '%') AND
t1.serveur = t3.serveur_court;
Thanks for your help!
Please try with the following query
SELECT t1.*, CONCAT(groupe, ' status ', scheduled_backup) AS etat_groupe,
CONCAT(groupe, ' status ', groupe_actif) AS etat_groupe_actif,
t3.volume_sauvegarde, t3.volume_externalise, t3.volume_replique
into planification_finale_asset2_test from planification_client_biens_group_test t1
LEFT OUTER JOIN volumetrie_1_jour t3
ON t1.nom LIKE CONCAT(t3.client, '%') AND
t1.serveur = t3.serveur_court;
It will load the data to your table planification_finale_asset2_test.

Optimizing Postgres query with timestamp filter

I have a query:
SELECT DISTINCT ON (analytics_staging_v2s.event_type, sent_email_v2s.recipient, sent_email_v2s.sent) sent_email_v2s.id, sent_email_v2s.user_id, analytics_staging_v2s.event_type, sent_email_v2s.campaign_id, sent_email_v2s.recipient, sent_email_v2s.sent, sent_email_v2s.stage, sent_email_v2s.sequence_id, people.role, people.company, people.first_name, people.last_name, sequences.name as sequence_name
FROM "sent_email_v2s"
LEFT JOIN analytics_staging_v2s ON sent_email_v2s.id = analytics_staging_v2s.sent_email_v2_id
JOIN people ON sent_email_v2s.person_id = people.id
JOIN sequences on sent_email_v2s.sequence_id = sequences.id
JOIN users ON sent_email_v2s.user_id = users.id
WHERE "sent_email_v2s"."status" = 1
AND "people"."person_type" = 0
AND (sent_email_v2s.sequence_id = 1888) AND (sent_email_v2s.sent >= '2016-03-18')
AND "users"."team_id" = 1
When I run EXPLAIN ANALYZE on it, I get:
Then, if I change that to the following (Just removing the (sent_email_v2s.sent >= '2016-03-18')) as follows:
SELECT DISTINCT ON (analytics_staging_v2s.event_type, sent_email_v2s.recipient, sent_email_v2s.sent) sent_email_v2s.id, sent_email_v2s.user_id, analytics_staging_v2s.event_type, sent_email_v2s.campaign_id, sent_email_v2s.recipient, sent_email_v2s.sent, sent_email_v2s.stage, sent_email_v2s.sequence_id, people.role, people.company, people.first_name, people.last_name, sequences.name as sequence_name
FROM "sent_email_v2s"
LEFT JOIN analytics_staging_v2s ON sent_email_v2s.id = analytics_staging_v2s.sent_email_v2_id
JOIN people ON sent_email_v2s.person_id = people.id
JOIN sequences on sent_email_v2s.sequence_id = sequences.id
JOIN users ON sent_email_v2s.user_id = users.id
WHERE "sent_email_v2s"."status" = 1
AND "people"."person_type" = 0
AND (sent_email_v2s.sequence_id = 1888) AND "users"."team_id" = 1
when I run EXPLAIN ANALYZE on this query, the results are:
EDIT:
The results above from today are about as I expected. When I ran this last night, however, the difference created by including the timestamp filter was about 100x slower (0.5s -> 59s). The EXPLAIN ANALYZE from last night showed all of the time increase to be attributed to the first unique/sort operation in the query plan above.
Could there be some kind of caching issue here? I am worried now that there might be something else going on (transiently) that might make this query take 100x longer since it happened at least once.
Any thoughts are appreciated!

Turning a nested select into a left join, with a max(date) condition

This is seemingly way too expensive. Can someone help me turn alter to fit a left join? The max(dateprocessed) syntax is killing me.
SELECT a.container, a.blnumber, a.bookingnumber, a.dateprocessed
FROM tracking_buffer_archive a, (SELECT container, blnumber, bookingnumber, max(dateprocessed)
AS max_date FROM tracking_buffer_archive GROUP BY container) b
WHERE
a.bookingnumber = '26007465580A'
and a.container = b.container
and a.blnumber = b.blnumber
AND a.dateprocessed = b.max_date
Thanks in advance!

PostgreSQL view embedded if-statements

In my database, for stores that have no rating from Reseller Ratings, they still have an entry but have -1.0 instead of a number between 0.0 and 10.0. The following query results in -10.00 showing up in my view for those stores with -1.0. Instead, I would like either nothing or a - showing up in its place, but I'm not very comfortable with implementing embedded if-statements in my view. Here is my current view.
CREATE VIEW myview AS
SELECT co_url_name AS company_url, score_combined AS stella_score, trunc(score*10, 2) AS bizrate_score,
(SELECT trunc("lifetimeRating"*10, 2)) AS resellerRating_score
FROM ss_profile_co AS s LEFT OUTER JOIN "resellerRatings_ratings" AS r
ON s.id = r.company_id
LEFT OUTER JOIN (SELECT * FROM bizrate_bizrate_ratings WHERE score_name = 'Overall rating') AS b
ON s.id = b.fk_co_id
ORDER BY co_url_name ASC;
The line (SELECT trunc("lifetimeRating"*10, 2)) AS resellerRating_score is the one that returns the negative numbers (or, for valid entries, will return a score between 0.00 and 100.00).
Obviously, I could simply remove these entries from the database that result in this, but it's half a learning experience and half out of my hands to do so anyways.
I appreciate the help!
EDIT: Attempted an embedded if but not surprisingly got an error.
IF (SELECT trunc("lifetimeRating"*10, 2)) = -10.00 THEN NULL ELSE (SELECT trunc("lifetimeRating"*10, 2)) AS resellerRating_score
EDIT2: Figured it out. Line in question is as follows:
(SELECT trunc("lifetimeRating"*10, 2) WHERE trunc("lifetimeRating"*10, 2) > 0) AS resellerrating_score
/foreveralone
Could look like this:
CREATE VIEW myview AS
SELECT co_url_name AS company_url
,score_combined AS stella_score
,trunc(score * 10, 2) AS bizrate_score
,CASE WHEN "lifetimeRating" < 0
THEN NULL
ELSE trunc("lifetimeRating" * 10, 2)
END AS resellerRating_score
FROM ss_profile_co s
LEFT JOIN "resellerRatings_ratings" r ON r.company_id = s.id
LEFT JOIN bizrate_bizrate_ratings b ON b.score_name = 'Overall rating'
AND b.fk_co_id = s.id
ORDER BY co_url_name;
Major points
Concerning your core question: the sub-select without a FROM clause serves no purpose. I simplified that and use a CASE statement instead.
I also simplified your LEFT JOIN to bizrate_bizrate_ratings. No sub-select necessary either. I pulled the WHERE clause up into the JOIN condition. Simpler and faster.
I would advise not to use mixed case identifiers, so you never have to use double quotes. (This probably makes #Daniels comment invalid, because lifetimerating != "lifetimeRating"