Improve select statement performance - sql

I'm with an Select performance issue, how can I make this SQL more efficient?
SELECT
O.DT_OCORRENCIA,
S.NU_SMP,
CLI.NM_APELIDO CLI,
TRANS.NM_ENTIDADE TRANS,
TPO.DS_TIPO_OCORRENCIA,
O.DS_OCORRENCIA,
REPLACE(FNC_RETORNA_MOTORISTAS(S.CD_SMP), '<br>', ';') AS NOME_MOTORISTA,
OG.DS_NOME AS DS_NOME_ORIGEM,
DG.DS_NOME AS DS_NOME_DESTINO,
U.NM_LOGIN AS DS_USUARIO_OCORRENCIA,
CASE
WHEN O.CD_USUARIO_INFORMOU = 717 THEN
'NAO'
ELSE
'SIM'
END FL_MANUAL,
CASE
WHEN (O.FL_ENVIOU_EMAIL_CLIENTE = 'S' OR O.FL_ENVIOU_EMAIL_TRANSP = 'S') THEN
'SIM'
ELSE
'NÃO'
END ENVIOU_EMAIL,
DECODE(O.NU_LOCAL_OCORRENCIA,
'1',
'Origem',
'2',
'Em transito',
'3',
'Alvos',
'4',
'Indiferente') DS_LOCAL_OCORRENCIA,
TOPER.DS_TIPO_OPERACAO
FROM TB_SMP S
INNER JOIN TB_OCORRENCIA O
ON O.CD_SMP = S.CD_SMP
INNER JOIN TB_TIPO_OCORRENCIA TPO
ON O.CD_TIPO_OCORRENCIA = TPO.CD_TIPO_OCORRENCIA
LEFT JOIN TB_TIPO_OPERACAO TOPER
ON TOPER.CD_TIPO_OPERACAO = S.CD_TIPO_OPERACAO
LEFT JOIN TB_USUARIO U
ON U.CD_USUARIO = O.CD_USUARIO_INFORMOU
LEFT JOIN TB_ENTIDADE CLI
ON CLI.CD_ENTIDADE = S.CD_ENTIDADE_CLIENTE
LEFT JOIN TB_ENTIDADE TRANS
ON TRANS.CD_ENTIDADE = S.CD_ENTIDADE_TRANSPORTADOR
LEFT JOIN TB_PONTO_GEOREFERENCIADO OG
ON OG.CD_PONTO_GEOREFERENCIADO = S.CD_PONTO_GEO_ORIGEM
LEFT JOIN TB_PONTO_GEOREFERENCIADO DG
ON (S.CD_PONTO_GEO_DESTINO IS NULL AND
DG.CD_PONTO_GEOREFERENCIADO =
FNC_GET_ULTIMA_ENTREGA_PONTO(S.CD_SMP))
OR (S.CD_PONTO_GEO_DESTINO IS NOT NULL AND
DG.CD_PONTO_GEOREFERENCIADO = S.CD_PONTO_GEO_DESTINO)
WHERE EXISTS (SELECT 1
FROM TB_TIPO_OCORRENCIA T
WHERE T.CD_TIPO_OCORRENCIA = O.CD_TIPO_OCORRENCIA)
AND S.DT_CADASTRO BETWEEN to_date('21/04/2014', 'dd/MM/yyyy') AND to_date('09/06/2014', 'dd/MM/yyyy')
AND O.DT_OCORRENCIA BETWEEN to_date('10/05/2014','dd/MM/yyyy') AND to_date('20/05/2014','dd/MM/yyyy')
AND S.cd_tipo_operacao in
(-1, 27, 11, 13, 37, 6, 7, 21, 12, 36, 28, 4, 5)
-- order by using linq?
ORDER BY CLI.NM_APELIDO,
TRANS.NM_APELIDO,
O.DT_OCORRENCIA,
DS_TIPO_OCORRENCIA
Here goes my execution plan:
PS.: I don't know nothing about sql tunnig :(

You can move some of the WHERE conditions to the JOIN conditions as you are doing an INNER JOIN on these tables, as below. Then, you would be operating on a smaller data set when you come to the LEFT JOIN conditions.
SELECT
O.DT_OCORRENCIA,
S.NU_SMP,
CLI.NM_APELIDO CLI,
TRANS.NM_ENTIDADE TRANS,
TPO.DS_TIPO_OCORRENCIA,
O.DS_OCORRENCIA,
REPLACE(FNC_RETORNA_MOTORISTAS(S.CD_SMP), '<br>', ';') AS NOME_MOTORISTA,
OG.DS_NOME AS DS_NOME_ORIGEM,
DG.DS_NOME AS DS_NOME_DESTINO,
U.NM_LOGIN AS DS_USUARIO_OCORRENCIA,
CASE
WHEN O.CD_USUARIO_INFORMOU = 717 THEN
'NAO'
ELSE
'SIM'
END FL_MANUAL,
CASE
WHEN (O.FL_ENVIOU_EMAIL_CLIENTE = 'S' OR O.FL_ENVIOU_EMAIL_TRANSP = 'S') THEN
'SIM'
ELSE
'NÃO'
END ENVIOU_EMAIL,
DECODE(O.NU_LOCAL_OCORRENCIA,
'1',
'Origem',
'2',
'Em transito',
'3',
'Alvos',
'4',
'Indiferente') DS_LOCAL_OCORRENCIA,
TOPER.DS_TIPO_OPERACAO
FROM TB_SMP S
INNER JOIN TB_OCORRENCIA O
ON O.CD_SMP = S.CD_SMP
AND S.DT_CADASTRO BETWEEN to_date('21/04/2014', 'dd/MM/yyyy') AND to_date('09/06/2014', 'dd/MM/yyyy')
AND O.DT_OCORRENCIA BETWEEN to_date('10/05/2014','dd/MM/yyyy') AND to_date('20/05/2014','dd/MM/yyyy')
AND S.cd_tipo_operacao in
(-1, 27, 11, 13, 37, 6, 7, 21, 12, 36, 28, 4, 5)
INNER JOIN TB_TIPO_OCORRENCIA TPO
ON O.CD_TIPO_OCORRENCIA = TPO.CD_TIPO_OCORRENCIA
LEFT JOIN TB_TIPO_OPERACAO TOPER
ON TOPER.CD_TIPO_OPERACAO = S.CD_TIPO_OPERACAO
LEFT JOIN TB_USUARIO U
ON U.CD_USUARIO = O.CD_USUARIO_INFORMOU
LEFT JOIN TB_ENTIDADE CLI
ON CLI.CD_ENTIDADE = S.CD_ENTIDADE_CLIENTE
LEFT JOIN TB_ENTIDADE TRANS
ON TRANS.CD_ENTIDADE = S.CD_ENTIDADE_TRANSPORTADOR
LEFT JOIN TB_PONTO_GEOREFERENCIADO OG
ON OG.CD_PONTO_GEOREFERENCIADO = S.CD_PONTO_GEO_ORIGEM
LEFT JOIN TB_PONTO_GEOREFERENCIADO DG
ON (S.CD_PONTO_GEO_DESTINO IS NULL AND
DG.CD_PONTO_GEOREFERENCIADO =
FNC_GET_ULTIMA_ENTREGA_PONTO(S.CD_SMP))
OR (S.CD_PONTO_GEO_DESTINO IS NOT NULL AND
DG.CD_PONTO_GEOREFERENCIADO = S.CD_PONTO_GEO_DESTINO)
-- order by using linq?
ORDER BY CLI.NM_APELIDO,
TRANS.NM_APELIDO,
O.DT_OCORRENCIA,
DS_TIPO_OCORRENCIA;
Adding indexes on the columns that are used for joining / filtering would help as well, especially on
TB_SMP.DT_CADASTRO
TB_SMP.cd_tipo_operacao
TB_OCORRENCIA.DT_OCORRENCIA
TB_ENTIDADE.CD_ENTIDADE

Related

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. :)

'Invalid object name' error when running query

When running query below I got error:
Msg 208, Level 16, State 1, Line 1 Invalid object name 't'
What I am doing wrong?
My query:
SELECT
t.ACCOUNTDATE
,t.PropertyName
,isnull(t.FOODREVENUE_TODAY,0) AS FOODREVENUE_TODAY_CY,isnull(y.FOODREVENUE_TODAY,0) AS FOODREVENUE_TODAY_PY
,isnull(t.FOODREVENUE_MTOD,0) AS FOODREVENUE_MTOD_CY,isnull(y.FOODREVENUE_MTOD,0) AS FOODREVENUE_MTOD_PY
,isnull(t.FOODREVENUE_YTOD,0) AS FOODREVENUE_YTOD_CY,isnull(y.FOODREVENUE_YTOD,0) AS FOODREVENUE_YTOD_PY
,isnull(t.LIQUORREVENUE_TODAY,0) AS LIQUORREVENUE_TODAY_CY,isnull(y.LIQUORREVENUE_TODAY,0) AS LIQUORREVENUE_TODAY_PY
,isnull(t.LIQUORREVENUE_MTOD,0) AS LIQUORREVENUE_MTOD_CY,isnull(y.LIQUORREVENUE_MTOD,0) AS LIQUORREVENUE_MTOD_PY
,isnull(t.LIQUORREVENUE_YTOD,0) AS LIQUORREVENUE_YTOD_CY,isnull(y.LIQUORREVENUE_YTOD,0) AS LIQUORREVENUE_YTOD_PY
,isnull(t.SOFTDRINKSREVENUE_TODAY,0) AS SOFTDRINKSREVENUE_TODAY_CY,isnull(y.SOFTDRINKSREVENUE_TODAY,0) AS SOFTDRINKSREVENUE_TODAY_PY
,isnull(t.SOFTDRINKSREVENUE_MTOD,0) AS SOFTDRINKSREVENUE_MTOD_CY,isnull(y.SOFTDRINKSREVENUE_MTOD,0) AS SOFTDRINKSREVENUE_MTOD_PY
,isnull(t.SOFTDRINKSREVENUE_YTOD,0) AS SOFTDRINKSREVENUE_YTOD_CY,isnull(y.SOFTDRINKSREVENUE_YTOD,0) AS SOFTDRINKSREVENUE_YTOD_PY
,isnull(t.TOBACCOREVENUE_TODAY,0) AS TOBACCOREVENUE_TODAY_CY,isnull(y.TOBACCOREVENUE_TODAY,0) AS TOBACCOREVENUE_TODAY_PY
,isnull(t.TOBACCOREVENUE_MTOD,0) AS TOBACCOREVENUE_MTOD_CY,isnull(y.TOBACCOREVENUE_MTOD,0) AS TOBACCOREVENUE_MTOD_PY
,isnull(t.TOBACCOREVENUE_YTOD,0) AS TOBACCOREVENUE_YTOD_CY,isnull(y.TOBACCOREVENUE_YTOD,0) AS TOBACCOREVENUE_YTOD_PY
,isnull(t.OTHERREVENUE_TODAY,0) AS OTHERREVENUE_TODAY_CY,isnull(y.OTHERREVENUE_TODAY,0) AS OTHERREVENUE_TODAY_PY
,isnull(t.OtherRevenue_MTOD,0) AS OTHERREVENUE_MTOD_CY,isnull(y.OtherRevenue_MTOD,0) AS OTHERREVENUE_MTOD_PY
,isnull(t.OTHERREVENUE_YTOD,0) AS OTHERREVENUE_YTOD_CY,isnull(y.OTHERREVENUE_YTOD,0) AS OTHERREVENUE_YTOD_PY
,isnull(t.FOODCOVERS_TODAY,0) AS FOODCOVERS_TODAY_CY,isnull(y.FOODCOVERS_TODAY,0) AS FOODCOVERS_TODAY_PY
,isnull(t.FOODCOVERS_MTOD,0) AS FOODCOVERS_MTOD_CY,isnull(y.FOODCOVERS_MTOD,0) AS FOODCOVERS_MTOD_PY
,isnull(t.FOODCOVERS_YTOD,0) AS FOODCOVERS_YTOD_CY,isnull(y.FOODCOVERS_YTOD,0) AS FOODCOVERS_YTOD_PY
,isnull(t.LIQUORCOVERS_TODAY,0) AS LIQUORCOVERS_TODAY_CY,isnull(y.LIQUORCOVERS_TODAY,0) AS LIQUORCOVERS_TODAY_PY
,isnull(t.LIQUORCOVERS_MTOD,0) AS LIQUORCOVERS_MTOD_CY,isnull(y.LIQUORCOVERS_MTOD,0) AS LIQUORCOVERS_MTOD_PY
,isnull(t.LIQUORCOVERS_YTOD,0) AS LIQUORCOVERS_YTOD_CY,isnull(y.LIQUORCOVERS_YTOD,0) AS LIQUORCOVERS_YTOD_PY
,isnull(t.OTHERCOVERS_TODAY,0) AS OTHERCOVERS_TODAY_CY,isnull(y.OTHERCOVERS_TODAY,0) AS OTHERCOVERS_TODAY_PY
,isnull(t.OTHERCOVERS_MTOD,0) AS OTHERCOVERS_MTOD_CY,isnull(y.OTHERCOVERS_MTOD,0) AS OTHERCOVERS_MTOD_PY
,isnull(t.OTHERCOVERS_YTOD,0) AS OTHERCOVERS_YTOD_CY,isnull(y.OTHERCOVERS_YTOD,0) AS OTHERCOVERS_YTOD_PY
,isnull(t.TOBACCOCOVERS_TODAY,0) AS TOBACCOCOVERS_TODAY_CY,isnull(y.TOBACCOCOVERS_TODAY,0) AS TOBACCOCOVERS_TODAY_PY
,isnull(t.TOBACCOCOVERS_MTOD,0) AS TOBACCOCOVERS_MTOD_CY,isnull(y.TOBACCOCOVERS_MTOD,0) AS TOBACCOCOVERS_MTOD_PY
,isnull(t.TOBACCOCOVERS_YTOD,0) AS TOBACCOCOVERS_YTOD_CY,isnull(y.TOBACCOCOVERS_YTOD,0) AS TOBACCOCOVERS_YTOD_PY
FROM (select B.FullDate AS ACCOUNTDATE
,C.PropertyName
,(A.FOODREVENUE) AS FOODREVENUE_TODAY,(D.FOODREVENUE_MTOD) AS FOODREVENUE_MTOD,(D.FOODREVENUE_YTOD) AS FOODREVENUE_YTOD
,(A.LIQUORREVENUE) AS LIQUORREVENUE_TODAY,(D.LIQUORREVENUE_MTOD) AS LIQUORREVENUE_MTOD,(D.LIQUORREVENUE_YTOD) AS LIQUORREVENUE_YTOD
,(A.SOFTDRINKSREVENUE) AS SOFTDRINKSREVENUE_TODAY,(D.SOFTDRINKSREVENUE_MTOD) AS SOFTDRINKSREVENUE_MTOD,(D.SOFTDRINKSREVENUE_YTOD) AS SOFTDRINKSREVENUE_YTOD
,(A.TOBACCOREVENUE) AS TOBACCOREVENUE_TODAY,(D.TOBACCOREVENUE_MTOD) AS TOBACCOREVENUE_MTOD,(D.TOBACCOREVENUE_YTOD) AS TOBACCOREVENUE_YTOD
,(A.OtherRevenue) AS OTHERREVENUE_TODAY,(D.OtherRevenue_MTOD) AS OTHERREVENUE_MTOD,(D.OTHERREVENUE_YTOD) AS OTHERREVENUE_YTOD
,(A.FOODCOVERS) AS FOODCOVERS_TODAY,(D.FOODCOVERS_MTOD) AS FOODCOVERS_MTOD,(D.FOODCOVERS_YTOD) AS FOODCOVERS_YTOD
,(A.LIQUORCOVERS) AS LIQUORCOVERS_TODAY,(D.LIQUORCOVERS_MTOD) AS LIQUORCOVERS_MTOD,(D.LIQUORCOVERS_YTOD) AS LIQUORCOVERS_YTOD
,(A.OTHERCOVERS) AS OTHERCOVERS_TODAY,(D.OTHERCOVERS_MTOD) AS OTHERCOVERS_MTOD,(D.OTHERCOVERS_YTOD) AS OTHERCOVERS_YTOD
,(A.TOBACCOCOVERS) AS TOBACCOCOVERS_TODAY,(D.TOBACCOCOVERS_MTOD) AS TOBACCOCOVERS_MTOD,(D.TOBACCOCOVERS_YTOD) AS TOBACCOCOVERS_YTOD
FROM Fact_MisCovers A
INNER JOIN DimDate B ON A.Datekey=B.DateKey
INNER JOIN Dim_MisCovers C ON A.Fact_MisCovers_id=C.Dim_MisCovers_id
INNER JOIN Fact_MisCovers D ON a.Fact_MisCovers_id=d.Fact_MisCovers_id) as t
LEFT JOIN t as y
ON DATEADD(YEAR,-1,t.ACCOUNTDATE) = y.ACCOUNTDATE
order by t.ACCOUNTDATE
Put your query in CTE, then select from it like:
;WITH cte AS (
(select B.FullDate AS ACCOUNTDATE
,C.PropertyName
,(A.FOODREVENUE) AS FOODREVENUE_TODAY,(D.FOODREVENUE_MTOD) AS FOODREVENUE_MTOD,(D.FOODREVENUE_YTOD) AS FOODREVENUE_YTOD
,(A.LIQUORREVENUE) AS LIQUORREVENUE_TODAY,(D.LIQUORREVENUE_MTOD) AS LIQUORREVENUE_MTOD,(D.LIQUORREVENUE_YTOD) AS LIQUORREVENUE_YTOD
,(A.SOFTDRINKSREVENUE) AS SOFTDRINKSREVENUE_TODAY,(D.SOFTDRINKSREVENUE_MTOD) AS SOFTDRINKSREVENUE_MTOD,(D.SOFTDRINKSREVENUE_YTOD) AS SOFTDRINKSREVENUE_YTOD
,(A.TOBACCOREVENUE) AS TOBACCOREVENUE_TODAY,(D.TOBACCOREVENUE_MTOD) AS TOBACCOREVENUE_MTOD,(D.TOBACCOREVENUE_YTOD) AS TOBACCOREVENUE_YTOD
,(A.OtherRevenue) AS OTHERREVENUE_TODAY,(D.OtherRevenue_MTOD) AS OTHERREVENUE_MTOD,(D.OTHERREVENUE_YTOD) AS OTHERREVENUE_YTOD
,(A.FOODCOVERS) AS FOODCOVERS_TODAY,(D.FOODCOVERS_MTOD) AS FOODCOVERS_MTOD,(D.FOODCOVERS_YTOD) AS FOODCOVERS_YTOD
,(A.LIQUORCOVERS) AS LIQUORCOVERS_TODAY,(D.LIQUORCOVERS_MTOD) AS LIQUORCOVERS_MTOD,(D.LIQUORCOVERS_YTOD) AS LIQUORCOVERS_YTOD
,(A.OTHERCOVERS) AS OTHERCOVERS_TODAY,(D.OTHERCOVERS_MTOD) AS OTHERCOVERS_MTOD,(D.OTHERCOVERS_YTOD) AS OTHERCOVERS_YTOD
,(A.TOBACCOCOVERS) AS TOBACCOCOVERS_TODAY,(D.TOBACCOCOVERS_MTOD) AS TOBACCOCOVERS_MTOD,(D.TOBACCOCOVERS_YTOD) AS TOBACCOCOVERS_YTOD
FROM Fact_MisCovers A
INNER JOIN DimDate B ON A.Datekey=B.DateKey
INNER JOIN Dim_MisCovers C ON A.Fact_MisCovers_id=C.Dim_MisCovers_id
INNER JOIN Fact_MisCovers D ON a.Fact_MisCovers_id=d.Fact_MisCovers_id)
)
SELECT
t.ACCOUNTDATE
,t.PropertyName
,isnull(t.FOODREVENUE_TODAY,0) AS FOODREVENUE_TODAY_CY,isnull(y.FOODREVENUE_TODAY,0) AS FOODREVENUE_TODAY_PY
,isnull(t.FOODREVENUE_MTOD,0) AS FOODREVENUE_MTOD_CY,isnull(y.FOODREVENUE_MTOD,0) AS FOODREVENUE_MTOD_PY
,isnull(t.FOODREVENUE_YTOD,0) AS FOODREVENUE_YTOD_CY,isnull(y.FOODREVENUE_YTOD,0) AS FOODREVENUE_YTOD_PY
,isnull(t.LIQUORREVENUE_TODAY,0) AS LIQUORREVENUE_TODAY_CY,isnull(y.LIQUORREVENUE_TODAY,0) AS LIQUORREVENUE_TODAY_PY
,isnull(t.LIQUORREVENUE_MTOD,0) AS LIQUORREVENUE_MTOD_CY,isnull(y.LIQUORREVENUE_MTOD,0) AS LIQUORREVENUE_MTOD_PY
,isnull(t.LIQUORREVENUE_YTOD,0) AS LIQUORREVENUE_YTOD_CY,isnull(y.LIQUORREVENUE_YTOD,0) AS LIQUORREVENUE_YTOD_PY
,isnull(t.SOFTDRINKSREVENUE_TODAY,0) AS SOFTDRINKSREVENUE_TODAY_CY,isnull(y.SOFTDRINKSREVENUE_TODAY,0) AS SOFTDRINKSREVENUE_TODAY_PY
,isnull(t.SOFTDRINKSREVENUE_MTOD,0) AS SOFTDRINKSREVENUE_MTOD_CY,isnull(y.SOFTDRINKSREVENUE_MTOD,0) AS SOFTDRINKSREVENUE_MTOD_PY
,isnull(t.SOFTDRINKSREVENUE_YTOD,0) AS SOFTDRINKSREVENUE_YTOD_CY,isnull(y.SOFTDRINKSREVENUE_YTOD,0) AS SOFTDRINKSREVENUE_YTOD_PY
,isnull(t.TOBACCOREVENUE_TODAY,0) AS TOBACCOREVENUE_TODAY_CY,isnull(y.TOBACCOREVENUE_TODAY,0) AS TOBACCOREVENUE_TODAY_PY
,isnull(t.TOBACCOREVENUE_MTOD,0) AS TOBACCOREVENUE_MTOD_CY,isnull(y.TOBACCOREVENUE_MTOD,0) AS TOBACCOREVENUE_MTOD_PY
,isnull(t.TOBACCOREVENUE_YTOD,0) AS TOBACCOREVENUE_YTOD_CY,isnull(y.TOBACCOREVENUE_YTOD,0) AS TOBACCOREVENUE_YTOD_PY
,isnull(t.OTHERREVENUE_TODAY,0) AS OTHERREVENUE_TODAY_CY,isnull(y.OTHERREVENUE_TODAY,0) AS OTHERREVENUE_TODAY_PY
,isnull(t.OtherRevenue_MTOD,0) AS OTHERREVENUE_MTOD_CY,isnull(y.OtherRevenue_MTOD,0) AS OTHERREVENUE_MTOD_PY
,isnull(t.OTHERREVENUE_YTOD,0) AS OTHERREVENUE_YTOD_CY,isnull(y.OTHERREVENUE_YTOD,0) AS OTHERREVENUE_YTOD_PY
,isnull(t.FOODCOVERS_TODAY,0) AS FOODCOVERS_TODAY_CY,isnull(y.FOODCOVERS_TODAY,0) AS FOODCOVERS_TODAY_PY
,isnull(t.FOODCOVERS_MTOD,0) AS FOODCOVERS_MTOD_CY,isnull(y.FOODCOVERS_MTOD,0) AS FOODCOVERS_MTOD_PY
,isnull(t.FOODCOVERS_YTOD,0) AS FOODCOVERS_YTOD_CY,isnull(y.FOODCOVERS_YTOD,0) AS FOODCOVERS_YTOD_PY
,isnull(t.LIQUORCOVERS_TODAY,0) AS LIQUORCOVERS_TODAY_CY,isnull(y.LIQUORCOVERS_TODAY,0) AS LIQUORCOVERS_TODAY_PY
,isnull(t.LIQUORCOVERS_MTOD,0) AS LIQUORCOVERS_MTOD_CY,isnull(y.LIQUORCOVERS_MTOD,0) AS LIQUORCOVERS_MTOD_PY
,isnull(t.LIQUORCOVERS_YTOD,0) AS LIQUORCOVERS_YTOD_CY,isnull(y.LIQUORCOVERS_YTOD,0) AS LIQUORCOVERS_YTOD_PY
,isnull(t.OTHERCOVERS_TODAY,0) AS OTHERCOVERS_TODAY_CY,isnull(y.OTHERCOVERS_TODAY,0) AS OTHERCOVERS_TODAY_PY
,isnull(t.OTHERCOVERS_MTOD,0) AS OTHERCOVERS_MTOD_CY,isnull(y.OTHERCOVERS_MTOD,0) AS OTHERCOVERS_MTOD_PY
,isnull(t.OTHERCOVERS_YTOD,0) AS OTHERCOVERS_YTOD_CY,isnull(y.OTHERCOVERS_YTOD,0) AS OTHERCOVERS_YTOD_PY
,isnull(t.TOBACCOCOVERS_TODAY,0) AS TOBACCOCOVERS_TODAY_CY,isnull(y.TOBACCOCOVERS_TODAY,0) AS TOBACCOCOVERS_TODAY_PY
,isnull(t.TOBACCOCOVERS_MTOD,0) AS TOBACCOCOVERS_MTOD_CY,isnull(y.TOBACCOCOVERS_MTOD,0) AS TOBACCOCOVERS_MTOD_PY
,isnull(t.TOBACCOCOVERS_YTOD,0) AS TOBACCOCOVERS_YTOD_CY,isnull(y.TOBACCOCOVERS_YTOD,0) AS TOBACCOCOVERS_YTOD_PY
FROM cte t
LEFT JOIN cte as y
ON DATEADD(YEAR,-1,t.ACCOUNTDATE) = y.ACCOUNTDATE
order by t.ACCOUNTDATE

The multi-part identifier could not be bound

SELECT
TOP (100) PERCENT
dbo.bARCM.CustGroup, dbo.bARCM.Customer,
CASE WHEN udJobType IN ('Scheduled Maintenance', 'Unscheduled Emergency',
'Unscheduled Call Out') THEN 'Maintenance'
WHEN udJobType IN ('Scheduled Special Projects', 'UPS Internal Capital Exp')
THEN 'Capital'
WHEN udJobType LIKE '%Turnaround%' THEN 'T/A'
END AS JobType,
CASE WHEN Factor = 1.0 THEN 'ST'
WHEN Factor = 1.5 THEN 'OT'
WHEN Factor = 2.0 THEN 'OT'
END AS STOT,
SUM(dbo.bJBID.Hours) AS Hours,
DATEADD(MONTH, DATEDIFF(MONTH, 0, dbo.bJBID.JCDate), 0) as SortMonth
FROM
dbo.bJBID
INNER JOIN
dbo.bJBIN ON dbo.bJBID.JBCo = dbo.bJBIN.JBCo AND dbo.bJBID.BillMonth = dbo.bJBIN.BillMonth AND dbo.bJBID.BillNumber = dbo.bJBIN.BillNumber
INNER JOIN
dbo.bARCM
INNER JOIN
dbo.bJCCM ON dbo.bARCM.CustGroup = dbo.bJCCM.CustGroup AND dbo.bARCM.Customer = dbo.bJCCM.Customer
INNER JOIN
dbo.JCJMPM ON dbo.bJCCM.JCCo = dbo.JCJMPM.JCCo AND dbo.bJCCM.Contract = dbo.JCJMPM.Contract ON dbo.bJBIN.JBCo = dbo.JCJMPM.JCCo AND
dbo.bJBIN.Contract = dbo.JCJMPM.Contract
INNER JOIN
dbo.bJCCT ON dbo.bJBID.CostType = dbo.bJCCT.CostType AND dbo.bJBID.PhaseGroup = dbo.bJCCT.PhaseGroup
INNER JOIN
dbo.budAcctMonths ON dbo.budAcctMonths.Month = dbo.bJBIN.BillMonth
WHERE
(dbo.bJCCM.JCCo = 1)
AND (dbo.bJBID.CostType IN (1, 41, 42, 43, 44, 45, 46))
AND (dbo.bJBID.CostTypeCategory = 'L')
AND (dbo.JCJMPM.udPlantLocation LIKE 'Deer%')
AND (dbo.bARCM.Name LIKE 'Dow%' OR dbo.bARCM.Name LIKE 'Rohm%')
GROUP BY
dbo.bARCM.CustGroup, dbo.bARCM.Customer,
dbo.JCJMPM.udJobType, dbo.bJBID.Factor, dbo.SortMonth
HAVING
(dbo.bARCM.CustGroup = 1) AND (SUM(dbo.bJBID.Hours) <> 0)
When I excute this query, I get
The multi-part identifier "dbo.SortMonth" could not be bound
error message. I am new to SQL, need some help.
Your SELECT is assigning a alias of SortMonth to the following DATEADD(MONTH, DATEDIFF(MONTH, 0, dbo.bJBID.JCDate), 0) but you cannot use an alias in GROUP BY unless it was named in a subquery.
You will need to change the code to:
GROUP BY dbo.bARCM.CustGroup,
dbo.bARCM.Customer,
dbo.JCJMPM.udJobType,
dbo.bJBID.Factor,
DATEADD(MONTH, DATEDIFF(MONTH, 0, dbo.bJBID.JCDate), 0) -- use the DATEADD code here not the alias

Linq - SQL query conversion

Can some one help me to convert this query to linq? I dont know how to use union and then sum in linq.
SELECT Patientname, SUM(A)AS Trec
FROM (SELECT Pm.Patientname, COUNT(*)AS A
FROM Facilitycheckinholdorder Fcho
INNER JOIN Medordertype Mot ON Fcho.Orderseq = Mot.Orderseq
JOIN Patientmaster Pm ON Mot.Patientseq = Pm.Patientseq
AND Fcho.Filleddate BETWEEN '2011-09-01 00:00:00:000' AND '2012-10-16 00:00:00:000'
AND Mot.Facilityid = 139
GROUP BY Pm.Patientname
UNION ALL
SELECT Pm.Patientname, COUNT(*)AS A
FROM Rxqdeliveryholdorder Rdho
INNER JOIN Medordertype Mot ON Rdho.Orderseq = Mot.Orderseq
JOIN Patientmaster Pm ON Mot.Patientseq = Pm.Patientseq
AND Rdho.Filleddate BETWEEN '2011-09-01 00:00:00:000' AND '2012-10-16 00:00:00:000'
AND Mot.Facilityid = 139
GROUP BY Pm.Patientname
) AS Trec
GROUP BY Patientname;
In fact this is not a real question, but I've tried my best...
var lst1 =
from fhco in facilitycheckinholdorder
join mot in meordertype on mot.orderseq equals fhco.orderseq
join pm in patientmaster on mot.patientseq equals pm.patientseq
where
fcho.FilledDate >= new DateTime(2011, 9, 1)
fcho.FilledDate <= new DateTime(2012, 10, 16)
select pm;
var lst2 =
from rdho in rxqdeliveryholdorder
join mot in meordertype on rdho.orderseq equals mot.orderseq
join pm in patientmaster on moit.patientseq equals pm.patientseq
where
fcho.FilledDate >= new DateTime(2011, 9, 1)
fcho.FilledDate <= new DateTime(2012, 10, 16)
select pm;
var res =
from item in lst1.Union(lst2)
select new { Name = item.patientname, Count = lst1.Count() + lst2.Count() };
Key points:
Your outermost query seems redundant.
Your names are not common C# style, and it makes them difficult to read.
UNION ALL corresponds to Concat, not Union.
Getting the Concat out of the way early lets you streamline the query. You could do this in the SQL.
.
var result =
from order in Queryable.Concat(
FacilityCheckInHoldOrder.Select(o => new { o.OrderSeq, o.FilledDate }),
RxqDeliveryHoldOrder .Select(o => new { o.OrderSeq, o.FilledDate }))
where order.FilledDate >= new DateTime(2011, 9, 1) &&
order.FilledDate < new DateTime(2012, 10, 16)
join type in MedOrderType.Where(t => t.FacilityID == 139)
on order.OrderSeq equals type.OrderSeq
join patient in PatientMaster
on type.PatientSeq equals patient.PatientSeq
group by patient.PatientName into grp
select new
{
PatientName = grp.Key,
Trec = grp.Count()
};

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