Create subquery using peewee, using `.select` on the subquery results - sql

I have a rather complex peewee query that looks like that:
SolutionAlias = Solution.alias()
fields = [
SolutionAlias.id.alias('solution_id'),
SolutionAlias.solver.id.alias('solver_id'),
SolutionAlias.exercise.id.alias('exercise_id'),
]
query = (
User
.select(*fields)
.join(Exercise, JOIN.CROSS)
.join(Course, JOIN.LEFT_OUTER, on=(Exercise.course == Course.id))
.join(SolutionAlias, JOIN.LEFT_OUTER, on=(
(SolutionAlias.exercise == Exercise.id)
& (SolutionAlias.solver == User.id)
))
.where(
(Exercise.id << self.get_exercise_ids()),
(User.id << self.get_user_ids()),
)
.group_by(Exercise.id, User.id, SolutionAlias.id)
.having(
(SolutionAlias.id == fn.MAX(SolutionAlias.id))
| (SolutionAlias.id.is_null(True))
)
.alias('solutions_subquery')
)
full_query_fields = [
query.c.solver_id,
query.c.exercise_id,
Solution.id.alias('solution_id'),
SolutionAssessment.icon.alias('assessment_icon'),
]
solutions = (
Solution
.select(*full_query_fields)
.join(query, JOIN.RIGHT_OUTER, on=(
Solution.id == query.c.solution_id
))
.join(SolutionAssessment, JOIN.LEFT_OUTER, on=(
(Solution.assessment == SolutionAssessment.id)
))
)
This one actually works, generating the following SQL query:
SELECT
"solutions_subquery"."solver_id",
"solutions_subquery"."exercise_id",
"t1"."id" AS "solution_id",
"t2"."icon" AS "assessment_icon"
FROM
"solution" AS "t1"
RIGHT OUTER JOIN (
SELECT
"t3"."id" AS "solution_id",
"t4"."id" AS "solver_id",
"t5"."id" AS "exercise_id"
FROM
"user" AS "t4" CROSS
JOIN "exercise" AS "t5"
LEFT OUTER JOIN "course" AS "t6" ON ("t5"."course_id" = "t6"."id")
LEFT OUTER JOIN "solution" AS "t3" ON (
("t3"."exercise_id" = "t5"."id")
AND ("t3"."solver_id" = "t4"."id")
)
WHERE
(
(
"t5"."id" IN (155, 156, 157)
)
AND (
"t4"."id" IN (1, 24, 25, 26, 27, 28)
)
)
GROUP BY
"t5"."id",
"t4"."id",
"t3"."id"
HAVING
(
(
"t3"."id" = MAX("t3"."id")
)
OR ("t3"."id" IS NULL)
)
) AS "solutions_subquery" ON (
"t1"."id" = "solutions_subquery"."solution_id"
)
LEFT OUTER JOIN "solutionassessment" AS "t2" ON ("t1"."assessment_id" = "t2"."id")
But I don't really want to use RIGHT_JOIN as it isn't supported by SQLite.
When trying to query using the subquery query and JOINing the Solution table into the subquery's result, I get an error from peewee.
The new query:
solutions = (
query
.select(*full_query_fields)
.join(Solution, JOIN.LEFT_OUTER, on=(
Solution.id == query.c.solution_id
))
.join(SolutionAssessment, JOIN.LEFT_OUTER, on=(
(Solution.assessment == SolutionAssessment.id)
))
)
The generated query:
SELECT
"solutions_subquery"."solver_id",
"solutions_subquery"."exercise_id",
"t1"."id" AS "solution_id",
"t1"."checker_id",
"t1"."state",
"t1"."submission_timestamp",
"t2"."name" AS "assessment",
"t2"."icon" AS "assessment_icon"
FROM
"user" AS "t3" CROSS
JOIN "exercise" AS "t4"
LEFT OUTER JOIN "course" AS "t5" ON ("t4"."course_id" = "t5"."id")
LEFT OUTER JOIN "solution" AS "t6" ON (
("t6"."exercise_id" = "t4"."id")
AND ("t6"."solver_id" = "t3"."id")
)
LEFT OUTER JOIN "solution" AS "t1" ON (
"t1"."id" = "solutions_subquery"."solution_id"
)
LEFT OUTER JOIN "solutionassessment" AS "t2" ON ("t1"."assessment_id" = "t2"."id")
WHERE
(
(
"t4"."id" IN (155, 156, 157)
)
AND (
"t3"."id" IN (1, 24, 25, 26, 27, 28)
)
)
GROUP BY
"t4"."id",
"t3"."id",
"t6"."id"
HAVING
(
(
"t6"."id" = MAX("t6"."id")
)
OR ("t6"."id" IS NULL)
)
Which results in:
psycopg2.errors.UndefinedTable: missing FROM-clause entry for table "solutions_subquery"
LINE 1: ...EFT OUTER JOIN "solution" AS "t1" ON ("t1"."id" = "solutions...
During handling of the above exception, another exception occurred:
[Truncated for readability...]
loguru.logger.critical(str(list(solutions.dicts().execute())))
[Truncated for readability...]
peewee.ProgrammingError: missing FROM-clause entry for table "solutions_subquery"
LINE 1: ...EFT OUTER JOIN "solution" AS "t1" ON ("t1"."id" = "solutions...
Why does peewee flatten the query? Is there another way to use LEFT_JOIN?

Eventually found the Select function in the documentation, which allows me to kind of wrap the previous query:
solutions = (
Select(columns=full_query_fields)
.from_(query)
.join(Solution, JOIN.LEFT_OUTER, on=(
Solution.id == query.c.solution_id
))
.join(SolutionAssessment, JOIN.LEFT_OUTER, on=(
(Solution.assessment == SolutionAssessment.id)
))
)
This solution works.

Related

left outer join Lambda

All,
I have multiple left outer join from multiple tables.
My SQL query works fine as below:
select distinct
C.CUST_CD, C.DSC, C.BH_PHONE, A.ADDRESS, CITY.DESCR CITY, ZIP.DESCR ZIP,
CSH.UDT_DT , CSR.DSC
from
dbo.CUST C
inner join dbo.CUST_ADDR A on C.CUST_CD = A.CUST_CD and A.ADDR_CD = 5
left outer join dbo.LOCATION CITY on A.CITY_CD = CITY.LOCATION_CD
left outer join dbo.LOCATION ZIP on A.ZIP_CD = ZIP.LOCATION_CD
left outer join dbo.CUST_STS S on C.CUST_STS_CD = S.CUST_STS_CD
left outer join dbo.CUST_STS_HIS CSH on C.CUST_CD = CSH.CUST_CD
left outer join dbo.CUST_STS_REASON CSR on CSH.REASON_CD = CSR.REASON_CD
where
C.CUST_STS_CD in (5)
and CSH.CUST_STS_CD in (5)
and CSR.STS_CD in (5)
order by C.CUST_CD
My Lambda expression looks like this:
var items = (
from a in db.CUSTs
from b in db.CUST_ADDR
.Where(bb => bb.CUST_CD == a.CUST_CD && bb.ADDR_CD ==5)
from c in db.LOCATION
.Where(cc => cc.LOCATION_CD == b.CITY_CD)
.DefaultIfEmpty() // <== makes outer left join
from d in db.LOCATION
.Where(dd => dd.LOCATION_CD == c.LOCATION_CD)
.DefaultIfEmpty()
from e in db.LOCATION
.Where(ee => ee.LOCATION_CD == b.ZIP_CD)
.DefaultIfEmpty()
from f in db.CUST_STS_HIS
.Where(ff => ff.CUST_STS_CD == a.CUST_STS_CD)
.DefaultIfEmpty()
from g in db.CUST_STS_REASON
.Where(gg => gg.STS_CD == f.CUST_STS_CD)
.DefaultIfEmpty()
where (a.CUST_STS_CD == 5 && f.CUST_STS_CD == 5 && g.STS_CD == 5)
select new
{
CUSTCode = a.CUST_CD,
CUSTDesc = a.DSC,
CUSTPhone = a.BH_PHONE,
CUSTAddr = a.ADDRESS,
CUSTCity = c.DESCR,
CUSTZip = d.DESCR,
CUSTCounty = e.DESCR,
Date = f.UDT_DT,
reason = g.DSC
})
.ToList();
Here's the SQL from the Lamda expression:
SELECT
1 AS [C1],
[Filter1].[CUST_CD1] AS [CUST_CD],
[Filter1].[DSC] AS [DSC],
[Filter1].[BH_PHONE] AS [BH_PHONE],
[Filter1].[ADDRESS] AS [ADDRESS],
[Filter1].[DESCR1] AS [DESCR],
[Filter1].[DESCR2] AS [DESCR1],
[Filter1].[DESCR3] AS [DESCR2],
[Filter1].[UDT_DT] AS [UDT_DT],
[Extent7].[DSC] AS [DSC1]
FROM (SELECT [Extent1].[CUST_CD] AS [CUST_CD1], [Extent1].[DSC] AS [DSC], [Extent1].[BH_PHONE] AS [BH_PHONE], [Extent1].[ADDRESS] AS [ADDRESS], [Extent3].[DESCR] AS [DESCR1], [Extent4].[DESCR] AS [DESCR2], [Extent5].[DESCR] AS [DESCR3], [Extent6].[UDT_DT] AS [UDT_DT], [Extent6].[CUST_STS_CD] AS [CUST_STS_CD1]
FROM [DBO].[CUST] AS [Extent1]
INNER JOIN (SELECT
[CUST_ADDR].[CUST_CD] AS [CUST_CD],
[CUST_ADDR].[ADDR_CD] AS [ADDR_CD],
[CUST_ADDR].[ADDRESS] AS [ADDRESS],
[CUST_ADDR].[CITY_CD] AS [CITY_CD],
[CUST_ADDR].[ZIP_CD] AS [ZIP_CD],
[CUST_ADDR].[STATE_CD] AS [STATE_CD],
[CUST_ADDR].[ADDRESS2] AS [ADDRESS2]
FROM [DBO].[CUST_ADDR] AS [CUST_ADDR]) AS [Extent2] ON ([Extent2].[CUST_CD] = [Extent1].[CUST_CD]) AND (cast(5 as decimal(18)) = [Extent2].[ADDR_CD])
LEFT OUTER JOIN [DBO].[LOCATION] AS [Extent3] ON [Extent3].[LOCATION_CD] = [Extent2].[CITY_CD]
LEFT OUTER JOIN [DBO].[LOCATION] AS [Extent4] ON [Extent4].[LOCATION_CD] = [Extent3].[LOCATION_CD]
LEFT OUTER JOIN [DBO].[LOCATION] AS [Extent5] ON [Extent5].[LOCATION_CD] = [Extent2].[ZIP_CD]
INNER JOIN (SELECT
[CUST_STS_HIS].[CUST_CD] AS [CUST_CD],
[CUST_STS_HIS].[UDT_DT] AS [UDT_DT],
[CUST_STS_HIS].[REASON_CD] AS [REASON_CD],
[CUST_STS_HIS].[CUST_STS_CD] AS [CUST_STS_CD],
[CUST_STS_HIS].[USR_ID] AS [USR_ID],
[CUST_STS_HIS].[NOTES] AS [NOTES]
FROM [DBO].[CUST_STS_HIS] AS [CUST_STS_HIS]) AS [Extent6] ON [Extent6].[CUST_STS_CD] = [Extent1].[CUST_STS_CD]
WHERE (cast(5 as decimal(18)) = [Extent1].[CUST_STS_CD]) AND (cast(5 as decimal(18)) = [Extent6].[CUST_STS_CD]) ) AS [Filter1]
INNER JOIN (SELECT
[CUST_STS_REASON].[STS_CD] AS [STS_CD],
[CUST_STS_REASON].[REASON_CD] AS [REASON_CD],
[CUST_STS_REASON].[DSC] AS [DSC],
[CUST_STS_REASON].[RES_KEY] AS [RES_KEY]
FROM [DBO].[CUST_STS_REASON] AS [CUST_STS_REASON]) AS [Extent7] ON [Extent7].[STS_CD] = [Filter1].[CUST_STS_CD1]
I am getting my SQL query results as expected (about 300 or so records). However, my lambda is bringing all records (over 100k). It is complete ignoring my "where" clause in the statement.
Could you please point me in the right direction on this query?
I appreciate your time and consideration.
Well, since there is more than one way of skinning a cat, I ended up creating, executing a Stored Procedure that solved the problem and returned only the data that I needed. Thank you for all your responses though. I really learned something new here. I appreciate!

Expression.Error Power Query EXCEL

I have a problem with a dynamic parameter in Power Query. There's the code:
let
Parametro = Excel.CurrentWorkbook(){[Name="Parametro"]}[Content],
InicioExec_Valor = Parametro{0}[Valor],
FimExec_Valor = Parametro{1}[Valor],
Fonte = Sql.Database("DATABASE", "TABLE", [Query="select#(lf)#(lf)o.cd_controle, exe.nm_pessoa AS Executante, o.numero AS OM, #(lf)CONVERT(nvarchar(10), o.dt_abertura, 103) AS Abertura,#(lf)o.medidor Horimetro_OM,#(lf)p.nm_pessoa AS Cliente, #(lf)e.nm_equipto AS Equipamento, pat.nr_patrimonio AS Patrimonio, #(lf)CONVERT(nvarchar(10), o.dt_autoriz_execucao, 103) AS Inicio_Exec, #(lf)CONVERT(nvarchar(10), o.dt_encos_oficina, 103) AS Fim_Exec, Z.nm_apelido AS Unidade, #(lf)CASE WHEN fl_preventiva = 'C' THEN 'Corretiva' #(lf)WHEN fl_preventiva = 'P' then 'PREVENTIVA'#(lf)WHEN fl_preventiva = 'R' then 'INSPEÇÃO RESUMIDA'#(lf)WHEN fl_preventiva = 'V' then 'INSPEÇÃO PREVENTIVA'#(lf)WHEN fl_preventiva = 'E' then 'ENTREGA TÉCNICA'#(lf)else 'Indefinido' end AS 'Corret_Preven'#(lf),CONVERT(nvarchar(10), fl_remessa.dt_saida, 103) AS DataSaida#(lf),fl_rem_equ.vl_medidor Horimetro_Remessa#(lf),CONVERT(nvarchar(10), o.dt_abertura, 103) AS Abertura#(lf),o.medidor Horimetro_OM#(lf)#(lf)from orcos o#(lf)inner join controle c on (c.cd_controle = o.cd_controle)#(lf)inner join wcore_oid oid on (oid.cd_oid = c.cd_oid)#(lf)left outer join empresa AS Z ON Z.cd_empresa = o.cd_empresa #(lf)left outer join equipto e on (e.cd_equipto = o.cd_equipto)#(lf)left outer join pessoa f on (f.cd_pessoa = o.cd_pessoa_tec)#(lf)left outer join pessoa p on (p.cd_pessoa = o.cd_pessoa)#(lf)left outer join pessoa exe on (exe.cd_pessoa = o.cd_pessoa_exe)#(lf)left outer join patrimon pat on (pat.cd_patrimonio = o.cd_patrimonio)#(lf)left outer join est_almox x on x.cd_almox = pat.cd_almox#(lf)left outer join empresa emp on emp.cd_empresa = o.cd_empresa_origem #(lf)#(lf)left outer JOIN dbo.fich_loc ON (fich_loc.cd_controle= o.cd_controle_loc)#(lf)left outer JOIN dbo.fl_remessa fl_remessa ON (fl_remessa.cd_controle = dbo.fich_loc.cd_controle)#(lf)#(lf)INNER JOIN(select max(fl_remessa.cd_flremessa)cd_flremessa, A.cd_controle #(lf)#(tab)#(tab)#(tab)#(tab)#(tab) from dbo.fl_remessa#(lf)#(tab)#(tab)#(tab)#(tab)#(tab) inner join dbsislocsalvador..fich_loc on (fl_remessa.cd_controle = dbo.fich_loc.cd_controle)#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) inner join dbsislocsalvador..orcos a on (fich_loc.cd_controle= A.cd_controle_loc#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) and fl_remessa.dt_saida<=a.dt_abertura) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) inner join controle c on (c.cd_controle = A.cd_controle)#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) left outer join patrimon pat on (pat.cd_patrimonio = a.cd_patrimonio)#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) LEFT OUTER JOIN dbo.fl_rem_equ AS fl_rem_equ ON pat.cd_patrimonio = fl_rem_equ.cd_patrimonio AND fl_remessa.cd_flremessa = fl_rem_equ.cd_flremessa#(lf) #(tab)#(tab) left outer JOIN dbo.loc_flremequ_xplano AS loc_flremequ_xplano ON loc_flremequ_xplano.cd_flremequ = fl_rem_equ.cd_flremequ #(lf) #(tab)#(tab)#(tab) left outer JOIN dbo.equipto AS equipto ON fl_rem_equ.cd_equipto = equipto.cd_equipto#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) where #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) ((NOT EXISTS(select top 1 * from config_tag_xoid)) OR (c.cd_oid not in (select txo.cd_oid from #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) (select * from ( select cd_tag, nm_tag , (30) as fl_acesso from config_tag t where t.fl_ativo in ('S') ) tags #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) WHERE (fl_acesso = 10) ) tags inner join config_tag_xoid txo on tags.cd_tag = txo.cd_tag where 3=3 /*filter_tag_clause*/ #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) group by txo.cd_oid))) and ( ( (a.cd_controle_loc is not null and a.cd_fldevolucao is null) ) ) and#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) (a.cd_empresa IN (24,45,5,46,20,29,43,15,48,10,1,22,8,34,49,9,47,52,7)) and ( ( a.cd_local is null or a.cd_local in (0,1,2,3,5,6,7,8,9) ) ) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) AND (a.cd_controle_loc IS NOT NULL) AND (a.cd_fldevolucao IS NULL) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) and (a.fl_preventiva in ('C', 'P', 'R', 'V', 'E')) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) and (equipto.cd_grupo in (1478, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1491, 1492, 1548, 1549))#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) group by a.cd_controle) AS fl_remessa_max #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) ON fl_remessa.cd_flremessa = fl_remessa_max.cd_flremessa#(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) and fl_remessa_max.cd_controle = o.cd_controle #(lf)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)LEFT OUTER JOIN dbo.fl_rem_equ AS fl_rem_equ ON pat.cd_patrimonio = fl_rem_equ.cd_patrimonio AND fl_remessa.cd_flremessa = fl_rem_equ.cd_flremessa#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab)#(tab) #(lf)left outer JOIN dbo.equipto AS equipto ON fl_rem_equ.cd_equipto = equipto.cd_equipto#(lf) #(tab)#(tab)#(tab)#(tab)#(tab) #(lf)WHERE ((NOT EXISTS(select top 1 * from config_tag_xoid)) OR (c.cd_oid not in (select txo.cd_oid from #(lf)(select * from ( select cd_tag, nm_tag , (30) as fl_acesso from config_tag t where t.fl_ativo in ('S') ) tags #(lf)WHERE (fl_acesso = 10) ) tags inner join config_tag_xoid txo on tags.cd_tag = txo.cd_tag where 3=3 /*filter_tag_clause*/ #(lf)group by txo.cd_oid))) and ( ( (o.cd_controle_loc is not null and o.cd_fldevolucao is null) ) ) and#(lf)(o.cd_empresa IN (24,45,5,46,20,29,43,15,48,10,1,22,8,34,49,9,47,52,7)) and ( ( o.cd_local is null or o.cd_local in (0,1,2,3,5,6,7,8,9) ) ) #(lf)AND (o.cd_controle_loc IS NOT NULL) AND (o.cd_fldevolucao IS NULL) #(lf)and (o.fl_preventiva in ('C', 'P', 'R', 'V', 'E')) #(lf)and (equipto.cd_grupo in (1478, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1491, 1492, 1548, 1549))"]),
#"Tipo Alterado" = Table.TransformColumnTypes(Fonte,{{"Abertura", type date}, {"Inicio_Exec", type date}, {"Fim_Exec", type date}, {"DataSaida", type date}}),
#"Colunas Removidas" = Table.RemoveColumns(#"Tipo Alterado",{"cd_controle", "Horimetro_OM2", "Abertura2"}),
#"Filtro Datas" = Table.SelectRows(#"Colunas Removidas", each [Fim_Exec] >= InicioExec_Valor and [Fim_Exec] <= FimExec_Valor)
in
#"Filtro Datas"
And occur that error:
Expression.Error: Não conseguimos aplicar o operador < aos tipos
Number e Date. Detalhes:
Operator=<
Left=42795
Right=01/06/2007
How can I solve that?
Note: MY PARAMETER (01/03/2017) ARE FORMATED AS TEXT.
Although I don't read Spanish, looks like it says you cannot compare number and date with < operator.
It is good practice, by the way, to first convert parameters to the proper type:
InicioExec_Valor = Date.From(Parametro{0}[Valor]),
FimExec_Valor = Date.From(Parametro{1}[Valor]),`
Try this.
If it won't work, determine step that generates error by clicking them one-by-one.
There is more I wonder about. Why do you convert Fim_Exec to nvarchar and then to date?
1. #(lf)CONVERT(nvarchar(10), o.dt_encos_oficina, 103) AS Fim_Exec
2. {"Fim_Exec", type date},
Why don't use Fim_Exec = CAST(o.dt_encos_oficina as date)? (or datetime, depending on SQL Server version) in the query?
Same applies to other columns.
Next, it is best practice not to use native queries unless absolutely required.
And, yes, this is largest and most complex query I've seen up to date. :)

Faster Query Execution

I have 42 columns and 4 joins in my table. Execution needs 140 seconds, I want to reduce the time of execution. What to do?
SELECT DISTINCT GR_ID,
CONVERT(VARCHAR, GR_DT, 106) AS GRDate,
GR_GN,
GR_GID,
GR_BS,
GR_BN,
GR_DC,
GR_COP,
GR_PA,
GR_AR,
GR_BG,
GR_SM,
GR_KG,
GR_IN,
GR_TS,
CMLC_BC,
CMLC_SC,
CMLC_KG,
CMLC_BL,
CMBC_BC,
CMBC_SC,
CMBC_KG,
CMBC_BL,
GR_BRN,
GR_BLC,
GR_LEA,
GR_ALF,
GR_BTA,
GR_PID,
GR_UTS,
GR_LR,
CMGB_BC,
CMGB_SC,
CMGB_KG,
CMGB_BL,
CMGB_LR,
GR_UPC,
GR_UPT,
GR_UTA,
GR_TTA,
GR_SPA,
GR_SAR,
GR_NR,
ISNULL(ACK_ACK, 'NO') AS ACK_ACK
FROM GR
LEFT JOIN CMBC
ON ( CMBC_ID = GR_GID )
AND ( CMBC_IID = GR_PID )
RIGHT JOIN CMLC
ON ( CMLC_ID = GR_GID )
AND ( CMLC_IID = GR_PID )
RIGHT JOIN CMGB
ON ( CMGB_ID = GR_GID )
AND ( CMGB_IID = GR_PID )
AND ( CMGB_TS = GR_UTS )
LEFT JOIN ACK
ON ( ACK_GN = GR_GN )
AND ( ACK_GID = GR_GID )
ORDER BY GR_GN,
GR_GID

Sql: Incorrect syntax near the keyword "as"

I have the following query. I'm not sure why it says the error in the title. I marked where is the error.
SELECT cmp.idcampanie,
spt.idspot,
spt.alias,
perioada =
(SELECT perioada
FROM dbo.tf_formatperioada(spt.datainceput, spt.datasfarsit)),
tipprogramare = tipprg.nume,
ora =
(SELECT ora
FROM dbo.tf_formatora(spt.ora, 0)),
spt.aliasex,
durata =
(SELECT durata
FROM dbo.tf_formatdurata(spt.durata)),
spt.coststandard,
spt.cost,
spt.nrdifuzari,
spt.valoare
FROM dbo.campanii AS cmp CROSS apply
(SELECT idspot, ALIAS, datainceput, datasfarsit, orafixa, tipprogramare, ora, aliasex, durata, coststandard, cost, nrdifuzari = sum(nrdifuzari), valoare = sum(valoare)
FROM dbo.tf_costurispoturi(cmp.idgrupmedia, cmp.idcampanie, cmp.datainceput, cmp.datasfarsit, cmp.idoferta, cmp.coeficienticostduratespoturi, cmp.coeficientcost, NULL)
WHERE idcanalmedia IS NOT NULL
GROUP BY idspot, ALIAS, datainceput, datasfarsit, orafixa, tipprogramare, ora, aliasex, durata, coststandard, cost) AS spt
INNER JOIN dbo.tipuriprogramari AS tipprg ON tipprg.orafixa = spt.orafixa
AND tipprg.tipprogramare = spt.tipprogramare
WHERE cmp.idgrupmedia = 1
AND cmp.datainceput <= '5.01.2014'
AND cmp.datasfarsit >= '5.30.2014'
ORDER BY cmp.idcampanie ASC,
spt.ALIAS ASC, spt.ora **AS spt** COMPUTE spt AS sptdtl BY idcampanie,
idspot,
ALIAS,
perioada,
tipprogramare) RELATE idcampanie TO idcampanie) AS spt
it gives error in order by
ORDER BY
cmp.idcampanie ASC,
spt.ALIAS ASC,
--spt.ora **AS spt** COMPUTE spt AS sptdtl
BY idcampanie,
idspot,
ALIAS,
perioada,
tipprogramare
)
RELATE idcampanie TO idcampanie) AS spt
Except this query is not give error, see query as below.
SELECT cmp.idcampanie,
spt.idspot,
spt.alias,
perioada = (SELECT perioada
FROM dbo.Tf_formatperioada(spt.datainceput,
spt.datasfarsit)),
tipprogramare = tipprg.nume,
ora = (SELECT ora
FROM dbo.Tf_formatora(spt.ora, 0)),
spt.aliasex,
durata = (SELECT durata
FROM dbo.Tf_formatdurata(spt.durata)),
spt.coststandard,
spt.cost,
spt.nrdifuzari,
spt.valoare
FROM dbo.campanii AS cmp
CROSS apply (SELECT idspot,
alias,
datainceput,
datasfarsit,
orafixa,
tipprogramare,
ora,
aliasex,
durata,
coststandard,
cost,
nrdifuzari = Sum(nrdifuzari),
valoare = Sum(valoare)
FROM dbo.Tf_costurispoturi(cmp.idgrupmedia,
cmp.idcampanie,
cmp.datainceput,
cmp.datasfarsit, cmp.idoferta,
cmp.coeficienticostduratespoturi,
cmp.coeficientcost,
NULL)
WHERE idcanalmedia IS NOT NULL
GROUP BY idspot,
alias,
datainceput,
datasfarsit,
orafixa,
tipprogramare,
ora,
aliasex,
durata,
coststandard,
cost) AS spt
INNER JOIN dbo.tipuriprogramari AS tipprg
ON tipprg.orafixa = spt.orafixa
AND tipprg.tipprogramare = spt.tipprogramare
WHERE cmp.idgrupmedia = 1
AND cmp.datainceput <= '5.01.2014'
AND cmp.datasfarsit >= '5.30.2014'

How do you add an item to a Unionized SQL View?

I am working to make an automated report in Crystal Reports which requires me to add in a table to an existing, pre-written view. The view contains a Union operation which is preventing me from using the view as normal. What I have done is manualy add-in the data (about halfway through).
The item required for the report is tblSOPartsUsed.Memo. which i have added into BOTH select queries. In the join between tblCustomerInventory and tblSOPartsUsed the .Memo table only appears in the PartsUsed table, not in the CustomerInventory.
First Select Query Location
tblCustomerInventory.SerialNumber AS ExchangeSerialNumber, **tblSOPartsUsed.Memo AS SOPartsNotes**, tblInvoiceDetail.Taxable AS DetailIsTaxable,
First From Query Location
tblCustomerInventory FULL OUTER JOIN
tblSOPartsUsed INNER JOIN
I have outlined the second Select and From in exactly the same way.
Can someone please shed some light, i've tried EVERYTHING!
The full code is below...
SELECT InvoiceAssemblyPriceBook.Features AS AssemblyFeatures,
tblInvoiceAssemblyDetail.EachQuantity AS AssemblyEachQuantity,
tblInvoiceAssemblyDetail.FKInvoiceDetail AS AssemblyFKInvoiceDetail,
tblInvoiceAssemblyDetail.InvoiceAssemblyDetailKeyID,
tblInvoiceAssemblyDetail.ItemID AS AssemblyItemID,
tblInvoiceAssemblyDetail.ItemDescription AS AssemblyItemDescription,
tblInvoiceAssemblyDetail.PrintOnInvoice AS AssemblyPrintOnInvoice,
tblInvoiceAssemblyDetail.Quantity AS AssemblyQuantity,
tblInvoiceAssemblyDetail.SellingPrice AS AssemblySellingPrice,
tblInvoiceAssemblyDetail.TotalSellingPrice AS AssemblyTotalSellingPrice,
tblInvoiceAssemblyDetail.Type AS AssemblyType,
tblInvoiceAssemblyDetail.UnitOfMeasure AS AssemblyUnitOfMeasure,
tblInvoiceDetail.AssemblyType AS DetailAssemblyType,
tblInvoiceDetail.InvoiceDetailKeyID,
tblInvoiceDetail.ItemDescription AS DetailItemDescription,
tblInvoiceDetail.ItemID AS DetailItemID,
tblInvoiceDetail.PrintOnInvoice AS DetailPrintOnInvoice,
tblInvoiceDetail.Quantity AS DetailQuantity,
tblInvoiceDetail.SellingPrice AS DetailSellingPrice,
tblInvoiceDetail.TotalSellingPrice AS DetailTotalSellingPrice,
tblInvoiceDetail.Type AS DetailType,
tblInvoices.AccountNumber,
tblInvoices.Comments,
tblInvoices.ContractNumber,
tblInvoices.Deposit,
tblInvoices.Freight,
tblInvoices.GSTax,
tblInvoices.InvoiceDate,
tblInvoices.InvoiceNumber,
tblInvoices.PaidDate,
tblInvoices.QuoteNumber,
tblInvoices.SalesTaxPercent,
CASE
WHEN tblInvoiceDetail.SoNumber IS NULL
THEN tblInvoices.SONumber
ELSE tblInvoiceDetail.SoNumber
END AS SONumber,
tblInvoices.STATUS,
tblInvoices.StatusDate,
tblInvoices.Tax,
tblInvoices.TotalAmountDue,
tblInvoices.TotalComment,
tblInvoices.TotalDollarsDiscounted,
tblInvoices.TotalGrossSell,
tblInvoices.TotalNetSell,
tblInvoices.TradeIn,
tblInvoices.WorkOrderNumber,
tblPriceLevels.IsRepairLevel,
tblServiceOrders.ContractNumber AS ServiceOrderContractNumber,
tblSysCompanySettings.HideGSTaxRelatedInformation,
tblSysCompanySettings.ItemsServicedPrintOnInvoice,
tblSysDisclaimerSettings.SalesInvoiceDisclaimer,
tblSysDisclaimerSettings.ServiceInvoiceDisclaimer,
tblSysPBSettings.PrintItemorPartNum,
VoidedByReps.RepName AS VoidedByRepName,
tblInvoices.TotalNetInvoice,
InvoiceDetailPriceBook.PartNumber AS DetailPartNumber,
InvoiceDetailPriceBook.UnitOfMeasure AS DetailUnitOfMeasure,
InvoiceDetailPriceBook.Features AS DetailFeatures,
tblSysDisclaimerSettings.ContractInvoiceDisclaimer,
tblInvoices.ProviderTax,
tblServiceOrders.BriefDescription AS SOBriefDescription,
tblInvoices.GSTaxComputedBeforeTradeIn,
tblInvoices.TaxComputedBeforeTradeIn,
tblInvoices.ProviderTaxRate,
tblInvoices.FreightTaxable,
tblInvoices.GSTIsTaxable,
tblInvoices.ProjectKeyID,
InvoicesReps.RepName,
tblAccounts.AccountNumber AS Expr1,
tblAccounts.AccountID,
tblInvoices.Terms,
tblInvoices.Reference,
tblInvoices.ARCustomerNumber,
tblInvoices.PONumber,
tblInvoices.ShipVia,
tblServiceOrders.DateRequested,
tblServiceOrders.DateOpened,
tblServiceOrders.SONumber AS ServiceOrderSONumber,
tblSysReportSettings.InvoiceCommentsAtEnd,
tblInvoices.SourceDocument,
tblTaxCodes.HasTieredDistrict,
tblExchange.ExchangeKeyID,
tblCustomerInventory.ItemID AS ExchangeItemID,
tblCustomerInventory.ItemDescription AS ExchangeItemDescription,
tblCustomerInventory.SerialNumber AS ExchangeSerialNumber,
tblSOPartsUsed.Memo AS SOPartsNotes,
tblInvoiceDetail.Taxable AS DetailIsTaxable,
tblInvoiceAssemblyDetail.Taxable AS AssemblyIsTaxable,
tblInvoices.IsFinalProgressiveInvoice,
tblInvoiceDetail.IsProgressiveInvoiceItem,
tblInvoices.IsProgressiveInvoice,
tblInvoices.TotalPriceCredited,
tblInvoices.TotalTaxCredited,
tblInvoices.TotalGSTaxCredited,
tblInvoices.TotalProviderTaxCredited,
tblInvoices.TotalFreightCredited,
tblInvoices.DiscountAllowed,
tblInvoices.AmountPaid,
(
SELECT MAX(SOItemsServicedKeyID) AS Expr1
FROM tblSOItemsServiced
WHERE (SONumber = tblServiceOrders.SONumber)
) AS SOItemsServicedKeyID,
tblInvoiceDetail.CommentOnly,
ServiceOrderContacts.ContactName AS SOContactName,
tblServiceOrders.ContactPhone AS SOContactPhone,
tblServiceOrders.ContactPhoneLocation AS SOContactPhoneLocation,
(
SELECT TOP (1) FormattedPhoneNumber
FROM tblPhoneNumbers
WHERE (ContactNumber = 0)
AND (PrimaryIndicator = 1)
AND (COALESCE(PhoneLocation, '') <> 'Fax')
AND (AccountNumber = tblAccounts.AccountNumber)
) AS AccountPhone,
(
SELECT TOP (1) PhoneLocation
FROM tblPhoneNumbers AS tblPhoneNumbers_1
WHERE (ContactNumber = 0)
AND (PrimaryIndicator = 1)
AND (COALESCE(PhoneLocation, '') <> 'Fax')
AND (AccountNumber = tblAccounts.AccountNumber)
) AS AccountPhoneLocation,
COALESCE(tvwr_TotalAmountDuePerAccount.AmountDue, 0.00) AS AmountDue,
COALESCE(tvwr_TotalAmountDuePerAccount.Unappliedpayments, 0.00) AS Unappliedpayments,
tblTaxCodes.IsHarmonizedTaxCode,
tblInvoices.GSTax + tblInvoices.Tax AS HSTax
FROM tblPriceBook AS InvoiceAssemblyPriceBook
RIGHT JOIN tblPriceBook AS InvoiceDetailPriceBook
RIGHT JOIN tblInvoiceAssemblyDetail
RIGHT JOIN tblCustomerInventory
FULL JOIN tblSOPartsUsed
INNER JOIN tblExchange
ON tblSOPartsUsed.SOPartsUsedKeyID = tblExchange.FKSOPartsUsed
ON tblCustomerInventory.CustomerInventoryKeyID = tblExchange.FKCustomerInventory RIGHT JOIN tblInvoiceDetail
ON tblSOPartsUsed.FKInvoiceDetail = tblInvoiceDetail.InvoiceDetailKeyID
ON tblInvoiceAssemblyDetail.FKInvoiceDetail = tblInvoiceDetail.InvoiceDetailKeyID
ON InvoiceDetailPriceBook.ItemID = tblInvoiceDetail.ItemID
ON InvoiceAssemblyPriceBook.ItemID = tblInvoiceAssemblyDetail.ItemID LEFT JOIN tblPriceLevels
ON tblInvoiceDetail.PriceLevel = tblPriceLevels.PriceLevelsKeyID RIGHT JOIN tvwr_TotalAmountDuePerAccount INNER JOIN tblAccounts
ON tvwr_TotalAmountDuePerAccount.AccountNumber = tblAccounts.AccountNumber RIGHT JOIN tblReps AS VoidedByReps RIGHT JOIN tblInvoices AS tblInvoices LEFT JOIN tblTaxCodes
ON tblInvoices.SalesTaxCode = tblTaxCodes.SalesTaxCode LEFT JOIN tblReps AS InvoicesReps
ON tblInvoices.SalesRep = InvoicesReps.RepNumber
ON VoidedByReps.RepNumber = tblInvoices.StatusBy LEFT JOIN tblServiceOrders LEFT JOIN tblContacts AS ServiceOrderContacts
ON tblServiceOrders.ContactNumber = ServiceOrderContacts.ContactNumber
ON tblInvoices.SONumber = tblServiceOrders.SONumber
ON tblAccounts.AccountNumber = tblInvoices.AccountNumber
ON tblInvoiceDetail.InvoiceNumber = tblInvoices.InvoiceNumber LEFT JOIN tblContacts AS tblContacts
ON tblAccounts.PrimaryContactNumber = tblContacts.ContactNumber CROSS JOIN tblSysPBSettings CROSS JOIN tblSysCompanySettings CROSS JOIN tblSysReportSettings CROSS JOIN tblSysDisclaimerSettings
WHERE (tblInvoices.MSPAgreementNumber = 0)
UNION ALL
SELECT InvoiceAssemblyPriceBook.Features AS AssemblyFeatures,
tblInvoiceAssemblyDetail.EachQuantity AS AssemblyEachQuantity,
tblInvoiceAssemblyDetail.FKInvoiceDetail AS AssemblyFKInvoiceDetail,
tblInvoiceAssemblyDetail.InvoiceAssemblyDetailKeyID,
tblInvoiceAssemblyDetail.ItemID AS AssemblyItemID,
tblInvoiceAssemblyDetail.ItemDescription AS AssemblyItemDescription,
tblInvoiceAssemblyDetail.PrintOnInvoice AS AssemblyPrintOnInvoice,
tblInvoiceAssemblyDetail.Quantity AS AssemblyQuantity,
tblInvoiceAssemblyDetail.SellingPrice AS AssemblySellingPrice,
tblInvoiceAssemblyDetail.TotalSellingPrice AS AssemblyTotalSellingPrice,
tblInvoiceAssemblyDetail.Type AS AssemblyType,
tblInvoiceAssemblyDetail.UnitOfMeasure AS AssemblyUnitOfMeasure,
tblInvoiceDetail.AssemblyType AS DetailAssemblyType,
tblInvoiceDetail.InvoiceDetailKeyID,
tblInvoiceDetail.ItemDescription AS DetailItemDescription,
tblInvoiceDetail.ItemID AS DetailItemID,
tblInvoiceDetail.PrintOnInvoice AS DetailPrintOnInvoice,
tblInvoiceDetail.Quantity AS DetailQuantity,
tblInvoiceDetail.SellingPrice AS DetailSellingPrice,
tblInvoiceDetail.TotalSellingPrice AS DetailTotalSellingPrice,
tblInvoiceDetail.Type AS DetailType,
tblInvoices.AccountNumber,
tblInvoices.Comments,
tblInvoices.ContractNumber,
tblInvoices.Deposit,
tblInvoices.Freight,
tblInvoices.GSTax,
tblInvoices.InvoiceDate,
tblInvoices.InvoiceNumber,
tblInvoices.PaidDate,
tblInvoices.QuoteNumber,
tblInvoices.SalesTaxPercent,
CASE
WHEN tblInvoiceDetail.SoNumber IS NULL
THEN tblInvoices.SONumber
ELSE tblInvoiceDetail.SoNumber
END AS SONumber,
tblInvoices.STATUS,
tblInvoices.StatusDate,
tblInvoices.Tax,
tblInvoices.TotalAmountDue,
tblInvoices.TotalComment,
tblInvoices.TotalDollarsDiscounted,
tblInvoices.TotalGrossSell,
tblInvoices.TotalNetSell,
tblInvoices.TradeIn,
tblInvoices.WorkOrderNumber,
tblPriceLevels.IsRepairLevel,
tblServiceOrders.ContractNumber AS ServiceOrderContractNumber,
tblSysCompanySettings.HideGSTaxRelatedInformation,
tblSysCompanySettings.ItemsServicedPrintOnInvoice,
tblSysDisclaimerSettings.SalesInvoiceDisclaimer,
tblSysDisclaimerSettings.MSPAgreementInvoiceDisclaimer AS ServiceInvoiceDisclaimer,
tblSysPBSettings.PrintItemorPartNum,
VoidedByReps.RepName AS VoidedByRepName,
tblInvoices.TotalNetInvoice,
InvoiceDetailPriceBook.PartNumber AS DetailPartNumber,
InvoiceDetailPriceBook.UnitOfMeasure AS DetailUnitOfMeasure,
InvoiceDetailPriceBook.Features AS DetailFeatures,
tblSysDisclaimerSettings.ContractInvoiceDisclaimer,
tblInvoices.ProviderTax,
tblServiceOrders.BriefDescription AS SOBriefDescription,
tblInvoices.GSTaxComputedBeforeTradeIn,
tblInvoices.TaxComputedBeforeTradeIn,
tblInvoices.ProviderTaxRate,
tblInvoices.FreightTaxable,
tblInvoices.GSTIsTaxable,
tblInvoices.ProjectKeyID,
InvoicesReps.RepName,
tblAccounts.AccountNumber AS Expr1,
tblAccounts.AccountID,
tblInvoices.Terms,
tblInvoices.Reference,
tblInvoices.ARCustomerNumber,
tblInvoices.PONumber,
tblInvoices.ShipVia,
tblServiceOrders.DateRequested,
tblServiceOrders.DateOpened,
tblServiceOrders.SONumber AS ServiceOrderSONumber,
tblSysReportSettings.InvoiceCommentsAtEnd,
tblInvoices.SourceDocument,
tblTaxCodes.HasTieredDistrict,
tblExchange.ExchangeKeyID,
tblCustomerInventory.ItemID AS ExchangeItemID,
tblCustomerInventory.ItemDescription AS ExchangeItemDescription,
tblCustomerInventory.SerialNumber AS ExchangeSerialNumber,
tblSOPartsUsed.Memo AS SOPartsNotes,
tblInvoiceDetail.Taxable AS DetailIsTaxable,
tblInvoiceAssemblyDetail.Taxable AS AssemblyIsTaxable,
tblInvoices.IsFinalProgressiveInvoice,
tblInvoiceDetail.IsProgressiveInvoiceItem,
tblInvoices.IsProgressiveInvoice,
tblInvoices.TotalPriceCredited,
tblInvoices.TotalTaxCredited,
tblInvoices.TotalGSTaxCredited,
tblInvoices.TotalProviderTaxCredited,
tblInvoices.TotalFreightCredited,
tblInvoices.DiscountAllowed,
tblInvoices.AmountPaid,
(
SELECT MAX(SOItemsServicedKeyID) AS Expr1
FROM tblSOItemsServiced
WHERE (SONumber = tblServiceOrders.SONumber)
) AS SOItemsServicedKeyID,
tblInvoiceDetail.CommentOnly,
ServiceOrderContacts.ContactName AS SOContactName,
tblServiceOrders.ContactPhone AS SOContactPhone,
tblServiceOrders.ContactPhoneLocation AS SOContactPhoneLocation,
(
SELECT TOP (1) FormattedPhoneNumber
FROM tblPhoneNumbers
WHERE (ContactNumber = 0)
AND (PrimaryIndicator = 1)
AND (COALESCE(PhoneLocation, '') <> 'Fax')
AND (AccountNumber = tblAccounts.AccountNumber)
) AS AccountPhone,
(
SELECT TOP (1) PhoneLocation
FROM tblPhoneNumbers AS tblPhoneNumbers_1
WHERE (ContactNumber = 0)
AND (PrimaryIndicator = 1)
AND (COALESCE(PhoneLocation, '') <> 'Fax')
AND (AccountNumber = tblAccounts.AccountNumber)
) AS AccountPhoneLocation,
COALESCE(tvwr_TotalAmountDuePerAccount.AmountDue, 0.00) AS AmountDue,
COALESCE(tvwr_TotalAmountDuePerAccount.Unappliedpayments, 0.00) AS Unappliedpayments,
COALESCE(tblTaxCodes.IsHarmonizedTaxCode, 0) AS IsHarmonizedTaxCode,
tblInvoices.GSTax + tblInvoices.Tax AS HSTax
FROM tblPriceBook AS InvoiceAssemblyPriceBook
RIGHT JOIN tblPriceBook AS InvoiceDetailPriceBook
RIGHT JOIN tblInvoiceAssemblyDetail
RIGHT JOIN tblCustomerInventory
FULL JOIN tblSOPartsUsed
INNER JOIN tblExchange
ON tblSOPartsUsed.SOPartsUsedKeyID = tblExchange.FKSOPartsUsed
ON tblCustomerInventory.CustomerInventoryKeyID = tblExchange.FKCustomerInventory RIGHT JOIN tblInvoiceDetail
ON tblSOPartsUsed.FKInvoiceDetail = tblInvoiceDetail.InvoiceDetailKeyID
ON tblInvoiceAssemblyDetail.FKInvoiceDetail = tblInvoiceDetail.InvoiceDetailKeyID
ON InvoiceDetailPriceBook.ItemID = tblInvoiceDetail.ItemID
ON InvoiceAssemblyPriceBook.ItemID = tblInvoiceAssemblyDetail.ItemID LEFT JOIN tblPriceLevels
ON tblInvoiceDetail.PriceLevel = tblPriceLevels.PriceLevelsKeyID RIGHT JOIN tvwr_TotalAmountDuePerAccount INNER JOIN tblAccounts
ON tvwr_TotalAmountDuePerAccount.AccountNumber = tblAccounts.AccountNumber RIGHT JOIN tblReps AS VoidedByReps RIGHT JOIN tblInvoices AS tblInvoices LEFT JOIN tblTaxCodes
ON tblInvoices.SalesTaxCode = tblTaxCodes.SalesTaxCode LEFT JOIN tblReps AS InvoicesReps
ON tblInvoices.SalesRep = InvoicesReps.RepNumber
ON VoidedByReps.RepNumber = tblInvoices.StatusBy LEFT JOIN tblServiceOrders LEFT JOIN tblContacts AS ServiceOrderContacts
ON tblServiceOrders.ContactNumber = ServiceOrderContacts.ContactNumber
ON tblInvoices.SONumber = tblServiceOrders.SONumber
ON tblAccounts.AccountNumber = tblInvoices.AccountNumber
ON tblInvoiceDetail.InvoiceNumber = tblInvoices.InvoiceNumber LEFT JOIN tblContacts AS tblContacts
ON tblAccounts.PrimaryContactNumber = tblContacts.ContactNumber CROSS JOIN tblSysPBSettings CROSS JOIN tblSysCompanySettings CROSS JOIN tblSysReportSettings CROSS JOIN tblSysDisclaimerSettings
WHERE (tblInvoices.MSPAgreementNumber <> 0)
I managed to copy each half of the view into a new view, manually tick off the tblSOPartsUsed.memo from the GUI and copied the two together which made the view work great