How to move variables from subquery to an outer query - postgres? - postgresql

I am writing query below and as you can see it has a lot of subqueries. I would like to throw out from subquery to outer query "dolzniki_terjatve.datum_vlozitve" and "dolzniki_terjatve.glavnica", so that I don't need to change them every time. I have tried many solutions which I have found here but nothing seems to work. Any guess?
select distinct on (upniki.naziv)
upniki.naziv,
b.stevilo,
b.glavnica_skupaj/b.stevilo as povprecna_glavnica,
b.glavnica_skupaj,
coalesce(taksa_vlozitve,0)+coalesce(dodatna_taksa,0) as celotna_sodna_taksa,
coalesce(stroski,0)-coalesce(taksa_vlozitve,0)+ coalesce(dodatni_odvetniski,0)as vsi_odvetniski_stroski,
coalesce(stroski_izvrsitelja,0) as stroski_izvrsitelja,
coalesce(pravdni,0) as pravdni,
coalesce(glavnicapok,0)+coalesce(glavnicapokobresti,0) as pokrivanje_glavice_z_obrestmi,
coalesce(poksodnataksavlozitve,0)+coalesce(poksodnataksavlozitveobresti,0)+coalesce(pokdodatnasodnataksa,0)+coalesce(pokdodatnasodnataksaobresti,0) as pokrivanje_takse_z_obrestmi,
coalesce(pokodvstroskivlozitve,0)+coalesce(pokodvstroskivlozitveobresti,0)+coalesce(pokdodatniodvstroski,0)+coalesce(pokdodatniodvstroskiobresti,0) as pokrivanje_odvetniskih_z_obrestmi,
coalesce(pokstroskiizvrsitelja,0)+coalesce(pokstroskiizvrsiteljaobresti,0) as pokrivanje_stroskov_izvrsitelja_z_obrestmi,
coalesce(pokpravdnistroski,0)+coalesce(pokpravdnistroskiobresti,0) as pokrivanje_pravdnih_z_obrestmi,
((coalesce(glavnicapok,0)+coalesce(glavnicapokobresti,0))/b.glavnica_skupaj) as uspesnosti_glavnice,
((coalesce(poksodnataksavlozitve,0)+coalesce(poksodnataksavlozitveobresti,0)+coalesce(pokdodatnasodnataksa,0)+coalesce(pokdodatnasodnataksaobresti,0))/(coalesce(taksa_vlozitve,0)+coalesce(dodatna_taksa,1))) as uspesnosti_taks,
((coalesce(pokodvstroskivlozitve,0)+coalesce(pokodvstroskivlozitveobresti,0)+coalesce(pokdodatniodvstroski,0)+coalesce(pokdodatniodvstroskiobresti,0))/(coalesce(stroski,0)-coalesce(taksa_vlozitve,0)+coalesce(dodatni_odvetniski,1))) as uspesnosti_odvetniskih_stroskov,
((coalesce(pokstroskiizvrsitelja,0)+coalesce(pokstroskiizvrsiteljaobresti,0))/coalesce(stroski_izvrsitelja,1)) as uspesnosti_stroskov_izvrsitelja,
((coalesce(pokpravdnistroski,0)+coalesce(pokpravdnistroskiobresti,0))/coalesce(pravdni,1)) as uspesnosti_pravdni,
coalesce(a.pokrivanje,0) as pokrivanje_glavnice_z_vsemi_placili,
(coalesce(a.pokrivanje,0)/b.glavnica_skupaj) as procent,
coalesce(taksa_vlozitve,0) as taksa_vlozitve,
coalesce(stroski,0)-coalesce(taksa_vlozitve) as odv_stroski_vlozitve,
coalesce(dodatna_taksa,0) as dodatna_taksa,
coalesce(dodatni_odvetniski,0) as dodatni_odvetniski,
coalesce(stroski_izvrsitelja,0)as stroski_izvrsitelja,
coalesce(pravdni,0) as pravdni_stroski,
coalesce(glavnicapok,0) as glavnicapok,
coalesce(glavnicapokobresti,0) as glavnicapokobresti,
coalesce (poksodnataksavlozitve,0) as poksodnataksavlozitve,
coalesce(poksodnataksavlozitveobresti) as poksodnataksavlozitveobresti,
coalesce (pokodvstroskivlozitve,0) as pokodvstroskivlozitve,
coalesce(pokodvstroskivlozitveobresti,0) as pokoodvstroskivlozitveobresti,
coalesce(pokdodatnasodnataksa,0) as pokdodatnasodnataksa,
coalesce(pokdodatnasodnataksaobresti,0) as pokdodatnasodnataksaobresti,
coalesce(pokdodatniodvstroski,0) as pokdodatniodvstroski,
coalesce(pokdodatniodvstroskiobresti,0) as pokdodatniodvstroskiobresti,
coalesce(pokstroskiizvrsitelja,0) as pokstroskiizvrsitelja,
coalesce(pokstroskiizvrsiteljaobresti,0) as pokstroskiizvrsiteljaobresti,
coalesce(pokpravdnistroski,0) as pokpravdnistroski,
coalesce(pokpravdnistroskiobresti,0) as pokpravdnistroskiobresti
from dolzniki_terjatve
inner join paketi on dolzniki_terjatve.id_paket=paketi.id_paket
inner join upniki on paketi.id_upnik=upniki.id_upnik
left join (select paketi.id_upnik, coalesce(sum(znesek),0)-coalesce(sum(preplacilo),0) as pokrivanje
from specifikacije1, dolzniki_terjatve, paketi
where specifikacije1.referenca=dolzniki_terjatve.referenca and dolzniki_terjatve.id_paket=paketi.id_paket
and datumplacila <=date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
group by paketi.id_upnik) as a on paketi.id_upnik=a.id_upnik
left join (select paketi.id_upnik, count(referenca) as stevilo, sum(glavnica) as glavnica_skupaj, coalesce(sum(stroski_vlozitve),0) as stroski, coalesce(sum(sodna_taksa_vlozitve),1) as taksa_vlozitve
from dolzniki_terjatve, paketi
where dolzniki_terjatve.id_paket=paketi.id_paket
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
group by paketi.id_upnik)
as b on paketi.id_upnik=b.id_upnik
left join (select paketi.id_upnik, sum(znesek) as dodatna_taksa
from dolzniki_dodatni_stroski, dolzniki_terjatve, paketi
where dolzniki_terjatve.referenca=dolzniki_dodatni_stroski.referenca and dolzniki_terjatve.id_paket=paketi.id_paket
and tip_stroskov='1'
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datum <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik)
as tabledodatnataksa on paketi.id_upnik=tabledodatnataksa.id_upnik
left join (select paketi.id_upnik, sum(znesek) as dodatni_odvetniski
from dolzniki_dodatni_stroski, dolzniki_terjatve, paketi
where dolzniki_terjatve.referenca=dolzniki_dodatni_stroski.referenca and dolzniki_terjatve.id_paket=paketi.id_paket
and tip_stroskov='2'
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01' and
datum <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik)
as tabledodatniodv on paketi.id_upnik=tabledodatniodv.id_upnik
left join (select paketi.id_upnik, coalesce(sum(znesek),0) as stroski_izvrsitelja
from dolzniki_dodatni_stroski, dolzniki_terjatve, paketi
where dolzniki_terjatve.referenca=dolzniki_dodatni_stroski.referenca and dolzniki_terjatve.id_paket=paketi.id_paket
and tip_stroskov='3'
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datum <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik)
as tablestroskiizv on paketi.id_upnik=tablestroskiizv.id_upnik
left join (select paketi.id_upnik, sum(znesek) as pravdni
from dolzniki_dodatni_stroski, dolzniki_terjatve, paketi
where dolzniki_terjatve.referenca=dolzniki_dodatni_stroski.referenca and dolzniki_terjatve.id_paket=paketi.id_paket
and tip_stroskov='4'
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-06-01'
and datum <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik) as tablepravdni on paketi.id_upnik=tablepravdni.id_upnik
left join (select paketi.id_upnik, sum(specifikacije_postavke.placilo) as glavnicapok
from specifikacije_postavke, specifikacije1, dolzniki_terjatve, paketi
where specifikacije1.idizracun=specifikacije_postavke.idizracun and dolzniki_terjatve.referenca=specifikacije1.referenca and paketi.id_paket=dolzniki_terjatve.id_paket
and postavka='1' and obresti=false
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datumplacila <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik)
as tabelaglavnice on paketi.id_upnik=tabelaglavnice.id_upnik
left join (select paketi.id_upnik, sum(specifikacije_postavke.placilo) as glavnicapokobresti
from specifikacije_postavke, specifikacije1, dolzniki_terjatve, paketi
where specifikacije1.idizracun=specifikacije_postavke.idizracun and dolzniki_terjatve.referenca=specifikacije1.referenca and paketi.id_paket=dolzniki_terjatve.id_paket
and postavka='1' and obresti=true
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datumplacila <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik)
as tabelaglavniceobresti on paketi.id_upnik=tabelaglavniceobresti.id_upnik
left join (select paketi.id_upnik, sum(specifikacije_postavke.placilo) as pokodvstroskivlozitve
from specifikacije_postavke, specifikacije1, dolzniki_terjatve, paketi
where specifikacije1.idizracun=specifikacije_postavke.idizracun and dolzniki_terjatve.referenca=specifikacije1.referenca and paketi.id_paket=dolzniki_terjatve.id_paket
and postavka='2' and obresti=false
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datumplacila <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik)
as tabelaodvstroski on paketi.id_upnik=tabelaodvstroski.id_upnik
left join (select paketi.id_upnik, sum(specifikacije_postavke.placilo) as pokodvstroskivlozitveobresti
from specifikacije_postavke, specifikacije1, dolzniki_terjatve, paketi
where specifikacije1.idizracun=specifikacije_postavke.idizracun and dolzniki_terjatve.referenca=specifikacije1.referenca and paketi.id_paket=dolzniki_terjatve.id_paket
and postavka='2' and obresti=true
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datumplacila <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik)
as tabelaodvstroskiobresti on paketi.id_upnik=tabelaodvstroskiobresti.id_upnik
left join (select paketi.id_upnik, sum(specifikacije_postavke.placilo) as poksodnataksavlozitve
from specifikacije_postavke, specifikacije1, dolzniki_terjatve, paketi
where specifikacije1.idizracun=specifikacije_postavke.idizracun and dolzniki_terjatve.referenca=specifikacije1.referenca and paketi.id_paket=dolzniki_terjatve.id_paket
and postavka='3' and obresti=false
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datumplacila <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik)
as tabelasodnataksavlozitve on paketi.id_upnik=tabelasodnataksavlozitve.id_upnik
left join (select paketi.id_upnik, sum(specifikacije_postavke.placilo) as poksodnataksavlozitveobresti
from specifikacije_postavke, specifikacije1, dolzniki_terjatve, paketi
where specifikacije1.idizracun=specifikacije_postavke.idizracun and dolzniki_terjatve.referenca=specifikacije1.referenca and paketi.id_paket=dolzniki_terjatve.id_paket
and postavka='3' and obresti=true
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datumplacila <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik)
as tabelasodnataksavlozitveobresti on paketi.id_upnik=tabelasodnataksavlozitveobresti.id_upnik
left join (select paketi.id_upnik, sum(specifikacije_postavke.placilo) as pokdodatnasodnataksa
from specifikacije_postavke, specifikacije1, dolzniki_terjatve, paketi
where specifikacije1.idizracun=specifikacije_postavke.idizracun and dolzniki_terjatve.referenca=specifikacije1.referenca and paketi.id_paket=dolzniki_terjatve.id_paket
and postavkastroski='1' and obresti=false
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datumplacila <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik)
as tabeladodatnasodnataksa on paketi.id_upnik=tabeladodatnasodnataksa.id_upnik
left join (select paketi.id_upnik, sum(specifikacije_postavke.placilo) as pokdodatnasodnataksaobresti
from specifikacije_postavke, specifikacije1, dolzniki_terjatve, paketi
where specifikacije1.idizracun=specifikacije_postavke.idizracun and dolzniki_terjatve.referenca=specifikacije1.referenca and paketi.id_paket=dolzniki_terjatve.id_paket
and postavkastroski='1' and obresti=true
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datumplacila <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik)
as tabeladodatnasodnataksaobresti on paketi.id_upnik=tabeladodatnasodnataksaobresti.id_upnik
left join (select paketi.id_upnik, sum(specifikacije_postavke.placilo) as pokdodatniodvstroski
from specifikacije_postavke, specifikacije1, dolzniki_terjatve, paketi
where specifikacije1.idizracun=specifikacije_postavke.idizracun and dolzniki_terjatve.referenca=specifikacije1.referenca and paketi.id_paket=dolzniki_terjatve.id_paket
and postavkastroski='2' and obresti=false
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datumplacila <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik)
as tabeladodatniodvstroski on paketi.id_upnik=tabeladodatniodvstroski.id_upnik
left join (select paketi.id_upnik, sum(specifikacije_postavke.placilo) as pokdodatniodvstroskiobresti
from specifikacije_postavke, specifikacije1, dolzniki_terjatve, paketi
where specifikacije1.idizracun=specifikacije_postavke.idizracun and dolzniki_terjatve.referenca=specifikacije1.referenca and paketi.id_paket=dolzniki_terjatve.id_paket
and postavkastroski='2' and obresti=true
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datumplacila <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik)
as tabeladodatniodvstroskiobresti on paketi.id_upnik=tabeladodatniodvstroskiobresti.id_upnik
left join (select paketi.id_upnik, sum(specifikacije_postavke.placilo) as pokstroskiizvrsitelja
from specifikacije_postavke, specifikacije1, dolzniki_terjatve, paketi
where specifikacije1.idizracun=specifikacije_postavke.idizracun and dolzniki_terjatve.referenca=specifikacije1.referenca and paketi.id_paket=dolzniki_terjatve.id_paket
and postavkastroski='3' and obresti=false
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datumplacila <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik)
as tabelastroskiizvrsitelja on paketi.id_upnik=tabelastroskiizvrsitelja.id_upnik
left join (select paketi.id_upnik, sum(specifikacije_postavke.placilo) as pokstroskiizvrsiteljaobresti
from specifikacije_postavke, specifikacije1, dolzniki_terjatve, paketi
where specifikacije1.idizracun=specifikacije_postavke.idizracun and dolzniki_terjatve.referenca=specifikacije1.referenca and paketi.id_paket=dolzniki_terjatve.id_paket
and postavkastroski='3' and obresti=true
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datumplacila <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik)
as tabelastroskiizvrsiteljaobresti on paketi.id_upnik=tabelastroskiizvrsiteljaobresti.id_upnik
left join (select paketi.id_upnik, sum(specifikacije_postavke.placilo) as pokpravdnistroski
from specifikacije_postavke, specifikacije1, dolzniki_terjatve, paketi
where specifikacije1.idizracun=specifikacije_postavke.idizracun and dolzniki_terjatve.referenca=specifikacije1.referenca and paketi.id_paket=dolzniki_terjatve.id_paket
and postavkastroski='4' and obresti=false
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datumplacila <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik)
as tabelapravdnistroski on paketi.id_upnik=tabelapravdnistroski.id_upnik
left join (select paketi.id_upnik, sum(specifikacije_postavke.placilo) as pokpravdnistroskiobresti
from specifikacije_postavke, specifikacije1, dolzniki_terjatve, paketi
where specifikacije1.idizracun=specifikacije_postavke.idizracun and dolzniki_terjatve.referenca=specifikacije1.referenca and paketi.id_paket=dolzniki_terjatve.id_paket
and postavkastroski='4' and obresti=true
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datumplacila <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik)
as tabelapravdnistroskiobresti on paketi.id_upnik=tabelapravdnistroskiobresti.id_upnik
where upniki.id_upnik in (131,141,1009, 1000)

We can define params in WITH section and use them in subqueries
Simple example
with
params as (select 1 param_from, 1 param_to)
select header_id, count(*) from position, params
where position.header_id between param_from and param_to
group by header_id
DB Fiddle to play with
Query after refactor
with
params as (select '2018-06-01'::timestamp p_datum_vlozitve_from, '2019-01-01'::timestamp p_datum_vlozitve_to)
select distinct on (upniki.naziv)
upniki.naziv,
b.stevilo,
....... original query .....
And instead of constans, values from param query can be used.
For example in tabledodatnataksa subquery
select paketi.id_upnik, sum(znesek) as dodatna_taksa
from dolzniki_dodatni_stroski, dolzniki_terjatve, paketi
where dolzniki_terjatve.referenca=dolzniki_dodatni_stroski.referenca and dolzniki_terjatve.id_paket=paketi.id_paket
and tip_stroskov='1'
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datum <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik
add param to tables and use p_datum_vlozitve_from instead of 2018-06-01 and p_datum_vlozitve_to instead of 2019-01-01
select paketi.id_upnik, sum(znesek) as dodatna_taksa
from dolzniki_dodatni_stroski, dolzniki_terjatve, paketi, param
where dolzniki_terjatve.referenca=dolzniki_dodatni_stroski.referenca and dolzniki_terjatve.id_paket=paketi.id_paket
and tip_stroskov='1'
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >=p_datum_vlozitve_from and dolzniki_terjatve.datum_vlozitve < p_datum_vlozitve_to
and datum <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik
Just small note
In JOIN subqueries there is a lot of repetitive code.. for example
tabledodatnataksa,tabledodatniodv,tablestroskiizv,tablepravdni
can be easily refactor to one subquery
select paketi.id_upnik,
sum(znesek) filter(where tip_stroskov='1') as dodatna_taksa,
sum(znesek) filter(where tip_stroskov='2') as dodatni_odvetniski,
coalesce(sum(znesek) filter(where tip_stroskov='3'),0) as stroski_izvrsitelja,
sum(znesek) filter(where tip_stroskov='4') as pravdni
from dolzniki_dodatni_stroski, dolzniki_terjatve, paketi
where dolzniki_terjatve.referenca=dolzniki_dodatni_stroski.referenca and dolzniki_terjatve.id_paket=paketi.id_paket
and dolzniki_terjatve.glavnica > 0 and dolzniki_terjatve.glavnica < 500
and dolzniki_terjatve.datum_vlozitve >='2018-06-01' and dolzniki_terjatve.datum_vlozitve < '2019-01-01'
and datum <= date(dolzniki_terjatve.datum_vlozitve) + interval '7 month'
group by paketi.id_upnik

Related

I'm trying to execute my Stored Procedure for some reason it doesn't allow me to

I've declared the parameters and inserted values in them however it won't allow me to execute my Stored Procedure. Any Help Please will be appreciated. I've tried to execute the Stored procedure in different ways and I still seem to be getting the same error Message.
Procedure has no parameters and arguments were supplied.
USE [ns_lots_of_vlfs]
go
/****** Object: StoredProcedure [dbo].[RestoreBackups] Script Date: 16/02/2023 10:49:09 ******/
SET ansi_nulls ON
go
SET quoted_identifier ON
go
ALTER PROCEDURE [dbo].[Restorebackups] (#DatabaseName VARCHAR(500),
#DatabaseNameCopy VARCHAR(5000),
#RestoreDate DATETIME,
#DiffDate DATETIME = NULL,
#LogDate DATETIME = NULL)
AS
DECLARE #FullBackupSQL NVARCHAR(max),
#DiffBackupSQL NVARCHAR(max),
#LogBackupSQL NVARCHAR(max),
#FullBackupDate DATETIME,
#FullBackupFile NVARCHAR(max),
#DiffBackupFile NVARCHAR(max),
#LogbackupFile NVARCHAR(max),
#FullBackupFileCopy VARCHAR(5000),
#FullBackupFileCopyldf VARCHAR(5000),
#FullBackupFileCopylocationldf VARCHAR(5000)
SET nocount ON
/* Gets the latest full backup to the restore date declared above for the database name declared above.*/
SELECT TOP 1 #FullBackupFile = bmf.physical_device_name,
#FullBackupDate = bs.backup_finish_date
FROM msdb.dbo.backupmediafamily bmf
INNER JOIN msdb.dbo.backupset bs
ON bs.media_set_id = bmf.media_set_id
WHERE bs.type = 'D'
AND bs.database_name = #DatabaseName
AND bs.backup_finish_date <= #RestoreDate
ORDER BY backup_finish_date DESC
IF NOT EXISTS(SELECT 1
FROM files
WHERE physical_device_name = #FullBackupFile)
INSERT INTO files
(family_sequence_number,
physical_device_name,
mirror,
backup_set_id,
backup_set_uuid)
SELECT TOP 1 family_sequence_number,
physical_device_name,
mirror,
backup_set_id,
backup_set_uuid
FROM msdb.dbo.backupmediafamily bmf
INNER JOIN msdb.dbo.backupset bs
ON bs.media_set_id = bmf.media_set_id
WHERE bs.type = 'D'
AND bs.database_name = #DatabaseName
AND bs.backup_finish_date <= #RestoreDate
AND NOT EXISTS (SELECT physical_device_name
FROM files
WHERE #FullBackupFile = physical_device_name)
ORDER BY backup_finish_date DESC
/* Gets me the latest full backup to the database name declared above. for the data file path location */
SELECT TOP 1 #FullBackupFileCopy =
Replace(sd.physical_name, #DatabaseName, #DatabaseNameCopy)
FROM sys.master_files sd
WHERE sd.type_desc = 'ROWS'
AND sd.physical_name LIKE '%.mdf'
AND sd.NAME = #DatabaseName
SELECT TOP 1 #FullBackupFileCopylocationldf =
Replace(sl.physical_name, #DatabaseName, #DatabaseNameCopy)
FROM sys.master_files sl
WHERE sl.NAME LIKE '%log'
AND sl.type_desc = 'LOG'
AND sl.NAME LIKE '%' + #DatabaseName + '%'
SELECT TOP 1 #FullBackupFileCopyldf = sl.NAME
FROM sys.master_files sl
WHERE sl.NAME LIKE '%log'
AND sl.type_desc = 'LOG'
AND sl.NAME LIKE '%' + #DatabaseName + '%'
SELECT TOP 1 #DiffDate = bs.backup_finish_date,
#DiffBackupFile = bmf.physical_device_name
FROM msdb.dbo.backupmediafamily bmf
INNER JOIN msdb.dbo.backupset bs
ON bs.media_set_id = bmf.media_set_id
WHERE bmf.physical_device_name LIKE '%diff%'
AND bs.backup_finish_date >= #FullBackupDate
AND bs.database_name = #DatabaseName
AND bs.backup_finish_date <= #RestoreDate
AND bs.type = 'I'
ORDER BY backup_finish_date DESC
IF NOT EXISTS(SELECT 1
FROM files
WHERE physical_device_name = #DiffBackupFile)
INSERT INTO files
(family_sequence_number,
physical_device_name,
mirror,
backup_set_id,
backup_set_uuid)
SELECT TOP 1 family_sequence_number,
physical_device_name,
mirror,
backup_set_id,
backup_set_uuid
FROM msdb.dbo.backupmediafamily bmf
INNER JOIN msdb.dbo.backupset bs
ON bs.media_set_id = bmf.media_set_id
WHERE bs.type = 'I'
AND bs.database_name = #DatabaseName
AND bs.backup_finish_date <= #RestoreDate
AND NOT EXISTS (SELECT physical_device_name
FROM files
WHERE #DiffBackupFile = physical_device_name)
ORDER BY backup_finish_date DESC
SET #FullBackupSQL = 'RESTORE DATABASE ' + #DatabaseNameCopy
+ ' FROM DISK = ''' + #FullBackupFile
+ ''' WITH NORECOVERY, MOVE '''
+ #DatabaseName + ''' TO '''
+ #FullBackupFileCopy + ''', MOVE '''
+ #FullBackupFileCopyldf + ''' TO '''
+ #FullBackupFileCopylocationldf
+ ''' , NORECOVERY,NOUNLOAD, STATS = 5'
SET #DiffBackupSQL = 'RESTORE DATABASE ' + #DatabaseNameCopy
+ ' FROM DISK = ''' + #DiffBackupFile
+ ''' WITH FILE = 1, NOUNLOAD, STATS = 5'
IF Object_id('tempdb..#TempTable_log') IS NOT NULL
DROP TABLE #temptable_log
SELECT bmf.family_sequence_number,
bmf.media_family_id,
bmf.media_count,
bmf.logical_device_name,
bmf.physical_device_name,
bmf.device_type,
bmf.physical_block_size,
bmf.mirror,
bs.backup_set_id,
bs.backup_set_uuid,
bs.first_family_number,
bs.first_media_number,
bs.last_family_number,
bs.last_media_number,
bs.catalog_family_number,
bs.catalog_media_number,
bs.position,
bs.expiration_date,
bs.software_vendor_id,
bs.NAME,
bs.description,
bs.user_name,
bs.software_major_version,
bs.software_minor_version,
bs.software_build_version,
bs.time_zone,
bs.mtf_minor_version,
bs.first_lsn,
bs.last_lsn,
bs.checkpoint_lsn,
bs.database_backup_lsn,
bs.database_creation_date,
bs.backup_start_date,
bs.backup_finish_date,
bs.type,
bs.sort_order,
bs.code_page,
bs.compatibility_level,
bs.database_version,
bs.backup_size,
bs.database_name,
bs.server_name,
bs.machine_name,
bs.flags,
bs.unicode_locale,
bs.unicode_compare_style,
bs.collation_name,
bs.is_password_protected,
bs.recovery_model,
bs.has_bulk_logged_data,
bs.is_snapshot,
bs.is_readonly,
bs.is_single_user,
bs.has_backup_checksums,
bs.is_damaged,
bs.begins_log_chain,
bs.has_incomplete_metadata,
bs.is_force_offline,
bs.is_copy_only,
bs.first_recovery_fork_guid,
bs.last_recovery_fork_guid,
bs.fork_point_lsn,
bs.database_guid,
bs.family_guid,
bs.differential_base_lsn,
bs.differential_base_guid,
bs.compressed_backup_size,
bs.key_algorithm,
bs.encryptor_thumbprint,
bs.encryptor_type
INTO #temptable_log
FROM msdb.dbo.backupmediafamily bmf
INNER JOIN msdb.dbo.backupset bs
ON bs.media_set_id = bmf.media_set_id
WHERE bs.database_name = #DatabaseName
AND bs.backup_finish_date <= #RestoreDate
AND bs.backup_finish_date > #FullBackupDate
AND bs.backup_finish_date > Isnull(#DiffDate, #FullBackupDate)
AND bs.type = 'L'
IF NOT EXISTS(SELECT 1
FROM files
WHERE physical_device_name = #LogbackupFile)
INSERT INTO files
SELECT *
FROM #temptable_log
WHERE physical_device_name NOT IN (SELECT physical_device_name
FROM files)
DECLARE #Counter INT
SET #Counter = 1
WHILE ( #Counter <= (SELECT Count(*)
FROM #temptable_log) )
BEGIN
SELECT TOP 1 #LogbackupFile = physical_device_name,
#LogBackupSQL = #LogbackupFile
FROM #temptable_log
WHERE backup_finish_date > Isnull(#DiffDate, #FullBackupDate)
AND backup_finish_date > #FullBackupDate
AND backup_finish_date <= #RestoreDate
ORDER BY backup_finish_date;
SET #Counter = 1 -- This should start at one --
/*every time you enter the while loop #counter is a new value so 1 then 2 then 3 and so on which retrieves this from the
temp table log.
*/
SET #LogBackupSQL = 'RESTORE LOG ' + #DatabaseNameCopy
+ ' FROM DISK = ''' + #LogbackupFile
+ ''' WITH FILE = 1, NOUNLOAD, STATS = 5,'
DELETE FROM #temptable_log
WHERE physical_device_name = #LogbackupFile;
END
EXEC master..Sp_executesql
#FullBackupSQL,
#DiffBackupSQL,
#LogBackupSQL
I try to execute this
USE [ns_lots_of_vlfs]
GO
DECLARE
#DatabaseName varchar(500) = 'ns_lots_of_vlfs',
#DatabaseNameCopy varchar(5000) = 'ns_lots_of_vlfs_COPY',
#RestoreDate datetime = '2023-02-13 15:45:00.000',
#DiffDate datetime = null,
#LogDate datetime = null
EXECUTE [dbo].[RestoreBackups] #DatabaseName, #DatabaseNameCopy, #RestoreDate
GO
I get this error message
Procedure has no parameters and arguments were supplied.

Power BI - SQL: Incorrect syntax near the keyword 'DECLARE'. Incorrect syntax near ')'

New to SQL and was given the query below to use in Power BI. It pulls the data table correctly on preview but fails when applying the change into Power BI Desktop. I don't know how to fix the syntax.
I get this error:
Power BI - SQL: Incorrect syntax near the keyword 'DECLARE'. Incorrect syntax near ')'.
Here is the query:
DECLARE #CLIENT AS NVARCHAR(32)
DECLARE #FULLVERSION AS NVARCHAR(10)
DECLARE #DATERUN AS DATETIME
DECLARE #ANON AS INT --1 to set anonymised mode on, 0 to set it to off
DECLARE #FROMDATE AS DATE --(FORMAT = YYYYMMDD) --UPDATE
DECLARE #TODATE AS DATE --(FORMAT = YYYYMMDD) --UPDATE
SET #CLIENT = 'HOGANS'
--SET #FULLVERSION = (SELECT MAX(BH_Version) FROM BH_Version)
SET #DATERUN = ( Getdate() )
SET #ANON = 0
SET #FROMDATE = '20211101' --(FORMAT = YYYYMMDD) --UPDATE
SET #TODATE = '20211231' --(FORMAT = YYYYMMDD) --UPDATE
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET nocount ON;
-- Insert statements for procedure here
SELECT #Client AS
ClientName,
#DATERUN AS DateRun,
#FROMDATE AS
QueryVariable_FromDate,
#TODATE AS
QueryVariable_ToDate,
-- #FULLVERSION as BHVersionWhenRun,
T.bh_taskguid,
RIGHT(Datepart(yy, T.bh_creationdate), 2)
+ RIGHT('00'+ CONVERT(NVARCHAR(2), Datepart(mm, T.bh_creationdate)), 2)
+ '-' + CONVERT(NVARCHAR, T.bh_referenceid) AS TaskID,
Auth.bh_userguid AS
AuthorGUID,
CASE
WHEN #ANON = 0 THEN Auth.bh_username
WHEN #ANON = 1 THEN NULL
END AS
AuthorName,
AuthDept.bh_departmentname AS
AuthorDepartmentName,
(SELECT TOP 1 AD.bh_departmentname
FROM bh_historic_report_departments AS AD
WHERE AuthDept.bh_parentguid = AD.bh_departmentguid) AS
AuthorDepartmentParent,
--THIS CHECKS THE HISTORIC DEPT STRUCTURE TO GET THE NAME OF THE PARENT DEPARTMENT OF THE AUTHOR
Sec.bh_userguid AS
CompletedByGUID,
CASE
WHEN #ANON = 0 THEN Sec.bh_username
WHEN #ANON = 1 THEN NULL
END AS
CompletedByName,
SecDept.bh_departmentname AS
CompletedByDepartmentName,
(SELECT TOP 1 SD.bh_departmentname
FROM bh_historic_report_departments AS SD
WHERE SecDept.bh_parentguid = SD.bh_departmentguid) AS
SecDepartmentParent,
--THIS CHECKS THE HISTORIC DEPT STRUCTURE TO GET THE NAME OF THE PARENT DEPARTMENT OF THE SECRETARY
CASE
WHEN #ANON = 0 THEN (SELECT TOP 1 HU.bh_username
--BH_UserGuid and remove the join for GUID only
FROM bh_historic_report_taskaudit HTA
INNER JOIN bh_historic_report_users AS HU
ON ( HU.bh_userguid =
HTA.bh_userguid )
WHERE ( HTA.bh_taskguid = T.bh_taskguid )
ORDER BY bh_auditid ASC)
WHEN #ANON = 1 THEN NULL
END AS
'Submitted By (Name)',
(SELECT TOP 1 bh_userguid
FROM bh_historic_report_taskaudit
WHERE ( bh_taskguid = T.bh_taskguid )
ORDER BY bh_auditid ASC) AS
'Submitted By (GUID)',
(SELECT bh_username
FROM bh_locks
WHERE bh_objectguid = t.bh_taskguid) AS
'Locked By',
CASE
WHEN (SELECT bh_username
FROM bh_locks
WHERE bh_objectguid = t.bh_taskguid) IS NULL THEN 'Pending'
WHEN Sec.bh_userguid IS NULL THEN 'In Progress'
ELSE 'Complete'
END AS
'TaskStatus',
CASE
WHEN (SELECT TOP 1 bh_userguid
FROM bh_historic_report_taskaudit
WHERE ( bh_taskguid = T.bh_taskguid )
ORDER BY bh_auditid ASC) = Auth.bh_userguid THEN 'Author'
ELSE 'On Behalf'
END AS
'Logged by',
WF.bh_workflowname AS
WorkflowName,
CASE
WHEN DT.bh_workflowname IS NOT NULL THEN DT.bh_workflowname
ELSE 'Not Configured'
END AS
'Work Type Should Go To',
CASE
WHEN ( DT.bh_workflowguid = T.bh_workflowguid ) THEN 'Correct Workflow'
--If no default workflow is specified then we assume this is sent to the correct workflow.
WHEN ( DT.bh_workflowguid IS NULL ) THEN 'No Default Workflow'
ELSE 'Incorrect Workflow'
END AS
'Sent To Correct Workflow',
-- ONLY POSSIBLE ON V5 AND ABOVE
CASE
WHEN ( T.bh_source = '15' ) -- Sent from Forms Desktop Assistant
--OR the below which includes iOS (10, 11), Android (12), Now Mail (4) and Hub (18)
OR ( T.bh_lengthintenths = '0'
AND T.bh_source IN ( '18', '10', '11', '12', '4' ) )
--AND T.BH_DocumentType NOT IN (SELECT BH_DocumentTypeName FROM BH_DocumentTypes)) -- assuming that if WT no longer exists and is zero length and is sent from Hub (i.e. not from Mobile, Classic etc which can't send Now tasks) then NOW
THEN 'TASK'
ELSE 'VOICE'
END AS
'Task Type (TASK or VOICE)',
--FOR V4, MANUALLY APPLYING ALL VOICE AS TASK TYPE
-- 'VOICE' as 'Task Type (NOW or VOICE)',
CASE
WHEN #ANON = 0 THEN T.bh_title
WHEN #ANON = 1 THEN NULL
ELSE NULL
END AS
'BH_Title',
T.bh_documenttype AS WorkType
,
T.bh_creationdate,
T.bh_senddate,
T.bh_sentpriority,
CASE
WHEN TA.priorities > 1 THEN 'YES'
ELSE 'NO'
END AS
'PriorityChanged',
T.bh_completiondate,
CASE
WHEN ( T.bh_requiredby IS NOT NULL )
AND ( T.bh_completiondate <= T.bh_requiredby ) THEN 'On Time'
WHEN ( T.bh_requiredby IS NOT NULL )
AND ( T.bh_completiondate > T.bh_requiredby ) THEN 'Overdue'
WHEN T.bh_requiredby IS NULL THEN 'No Deadline Set'
END AS OnTime,
T.bh_priorityname,
T.bh_requiredby,
CASE
WHEN TA.requiredby > 1 THEN 'YES'
ELSE 'NO'
END AS
'RequiredByChanged',
T.bh_sourcetimezone AS
TimeZoneOffset,
T.bh_turnaroundtime AS
TurnaroundTimeInSec,
--NOTE: this is the difference in seconds between the send date and the completion date
-- (
-- RIGHT('000' + CONVERT(VARCHAR, T.BH_TurnaroundTime / 3600 / 24),3) + ':'
-- + RIGHT('00' + CONVERT(VARCHAR, T.BH_TurnaroundTime / 3600 % 24),2) + ':'
-- + RIGHT('00' + CONVERT(VARCHAR, T.BH_TurnaroundTime / 60 % 60),2) + ':'
-- + RIGHT('00' + CONVERT(VARCHAR,T.BH_TurnaroundTime % 60),2)
-- ) AS TurnaroundTimeDays,
T.bh_numreassignments,
CASE
WHEN ( T.bh_source = '0' ) THEN 'Classic Client'
WHEN ( T.bh_source = '4' ) THEN 'Now Mail'
WHEN ( T.bh_source = '5' ) THEN 'Web Client'
WHEN ( T.bh_source = '6' ) THEN 'Windows Mobile'
WHEN ( T.bh_source = '7' ) THEN 'BlackBerry'
WHEN ( T.bh_source = '8' ) THEN 'Hosted Services Client'
WHEN ( T.bh_source = '9' ) THEN 'Work Manager'
WHEN ( T.bh_source = '10' ) THEN 'BigHand Go'
WHEN ( T.bh_source = '11' ) THEN 'BigHand Mobile iPhone'
WHEN ( T.bh_source = '12' ) THEN 'Android'
WHEN ( T.bh_source = '13' ) THEN 'BlackBerry 10'
WHEN ( T.bh_source = '14' ) THEN 'Windows Phone'
WHEN ( T.bh_source = '15' ) THEN 'BigHand Now'
WHEN ( T.bh_source = '16' ) THEN 'BigHand Go For Windows'
WHEN ( T.bh_source = '17' ) THEN 'BigHand Go For Windows Phone'
WHEN ( T.bh_source = '18' ) THEN 'Hub'
END AS 'Source'
,
T.bh_sourcetimezone,
--(
-- RIGHT('00' + CONVERT(VARCHAR, (T.BH_LengthInTenths/10) / 3600 % 24),2) + ':'
-- + RIGHT('00' + CONVERT(VARCHAR, (T.BH_LengthInTenths/10) / 60 % 60),2) + ':'
-- + RIGHT('00' + CONVERT(VARCHAR,(T.BH_LengthInTenths/10) % 60),2)
-- ) AS LengthInHours,
( T.bh_lengthintenths / 10 ) AS
LengthInSeconds,
( T.bh_lengthintenths / 10 ) / 60 AS
LengthInMins,
(SELECT Sum(Datediff(second, bh_startdate, bh_enddate))
FROM bh_historic_report_taskaudit
WHERE ( bh_taskguid = T.bh_taskguid )) AS
'Total Processing Time (Sec)',
--(
-- RIGHT('00' + CONVERT(VARCHAR, (SELECT sum(datediff(SECOND,BH_StartDate, BH_EndDate))
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND BH_StartDate >= T.BH_SendDate) / 3600 % 24),2) + ':'
--+ RIGHT('00' + CONVERT(VARCHAR, (SELECT sum(datediff(SECOND,BH_StartDate, BH_EndDate))
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND BH_StartDate >= T.BH_SendDate) / 60 % 60),2) + ':'
--+ RIGHT('00' + CONVERT(VARCHAR,(SELECT sum(datediff(SECOND,BH_StartDate, BH_EndDate))
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND BH_StartDate >= T.BH_SendDate) % 60),2)
--) AS TotalProcessingHours,
( Isnull((SELECT Sum(Datediff(second, bh_startdate, bh_enddate))
FROM bh_historic_report_taskaudit
WHERE ( bh_taskguid = T.bh_taskguid )
AND ( bh_userguid = T.bh_authorguid )), 0) ) AS
'Author Processing Time (Sec)',
--(ISNULL((
-- RIGHT('00' + CONVERT(VARCHAR, (SELECT sum(datediff(SECOND,BH_StartDate, BH_EndDate))
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND (BH_UserGuid = T.BH_AuthorGuid) AND (BH_StartDate >= T.BH_SendDate)) / 3600 % 24),2) + ':'
-- + RIGHT('00' + CONVERT(VARCHAR, (SELECT sum(datediff(SECOND,BH_StartDate, BH_EndDate))
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND (BH_UserGuid = T.BH_AuthorGuid) AND (BH_StartDate >= T.BH_SendDate)) / 60 % 60),2) + ':'
-- + RIGHT('00' + CONVERT(VARCHAR,(SELECT sum(datediff(SECOND,BH_StartDate, BH_EndDate))
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND (BH_UserGuid = T.BH_AuthorGuid) AND (BH_StartDate >= T.BH_SendDate)) % 60),2)), '00:00:00')
-- ) AS AuthorProcessingHours,
( Isnull((SELECT Sum(Datediff(second, bh_startdate, bh_enddate))
FROM bh_historic_report_taskaudit
WHERE ( bh_taskguid = T.bh_taskguid )
AND ( bh_userguid <> T.bh_authorguid )
AND ( bh_startdate >= T.bh_senddate )), 0) ) AS
'Non-Author Processing Time (Sec)',
--(ISNULL((
-- RIGHT('00' + CONVERT(VARCHAR, (SELECT sum(datediff(SECOND,BH_StartDate, BH_EndDate))
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND (BH_UserGuid <> T.BH_AuthorGuid) AND (BH_StartDate >= T.BH_SendDate)) / 3600 % 24),2) + ':'
--+ RIGHT('00' + CONVERT(VARCHAR, (SELECT sum(datediff(SECOND,BH_StartDate, BH_EndDate))
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND (BH_UserGuid <> T.BH_AuthorGuid) AND (BH_StartDate >= T.BH_SendDate)) / 60 % 60),2) + ':'
--+ RIGHT('00' + CONVERT(VARCHAR,(SELECT sum(datediff(SECOND,BH_StartDate, BH_EndDate))
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND (BH_UserGuid <> T.BH_AuthorGuid) AND (BH_StartDate >= T.BH_SendDate)) % 60),2)), '00:00:00')
--) AS NonAuthorProcessingHours,
(SELECT Sum(bh_playtime)
FROM bh_historic_report_taskaudit
WHERE ( bh_taskguid = T.bh_taskguid )
AND ( bh_startdate >= T.bh_senddate )) AS
'TotalPlay Time',
--(
-- RIGHT('00' + CONVERT(VARCHAR, (SELECT sum(BH_PlayTime)
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND (BH_StartDate >= T.BH_SendDate)) / 3600 % 24),2) + ':'
--+ RIGHT('00' + CONVERT(VARCHAR, (SELECT sum(BH_PlayTime)
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND (BH_StartDate >= T.BH_SendDate)) / 60 % 60),2) + ':'
--+ RIGHT('00' + CONVERT(VARCHAR,(SELECT sum(BH_PlayTime)
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND (BH_StartDate >= T.BH_SendDate)) % 60),2)
--) AS TotalPlaytimeHours,
( Isnull((SELECT Sum(bh_playtime)
FROM bh_historic_report_taskaudit
WHERE ( bh_taskguid = T.bh_taskguid )
AND ( bh_userguid = T.bh_authorguid )
AND ( bh_startdate >= T.bh_senddate )), 0) ) AS
'Author Play Time (Sec)',
-- (ISNULL((
-- RIGHT('00' + CONVERT(VARCHAR, (SELECT sum(BH_PlayTime)
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND (BH_UserGuid = T.BH_AuthorGuid) AND (BH_StartDate >= T.BH_SendDate)) / 3600 % 24),2) + ':'
-- + RIGHT('00' + CONVERT(VARCHAR, (SELECT sum(BH_PlayTime)
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND (BH_UserGuid = T.BH_AuthorGuid) AND (BH_StartDate >= T.BH_SendDate)) / 60 % 60),2) + ':'
-- + RIGHT('00' + CONVERT(VARCHAR,(SELECT sum(BH_PlayTime)
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND (BH_UserGuid = T.BH_AuthorGuid) AND (BH_StartDate >= T.BH_SendDate)) % 60),2)), '00:00:00' )
-- ) AS AuthorPlaytimeHours,
( Isnull((SELECT Sum(bh_playtime)
FROM bh_historic_report_taskaudit
WHERE ( bh_taskguid = T.bh_taskguid )
AND ( bh_userguid <> T.bh_authorguid )
AND ( bh_startdate >= T.bh_senddate )), 0) ) AS
'Non-Author Play Time (Sec)'
--(ISNULL((
-- RIGHT('00' + CONVERT(VARCHAR, (SELECT sum(BH_PlayTime)
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND (BH_UserGuid <> T.BH_AuthorGuid) AND (BH_StartDate >= T.BH_SendDate)) / 3600 % 24),2) + ':'
--+ RIGHT('00' + CONVERT(VARCHAR, (SELECT sum(BH_PlayTime)
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND (BH_UserGuid <> T.BH_AuthorGuid) AND (BH_StartDate >= T.BH_SendDate)) / 60 % 60),2) + ':'
--+ RIGHT('00' + CONVERT(VARCHAR,(SELECT sum(BH_PlayTime)
-- FROM BH_HISTORIC_REPORT_TASKAUDIT
-- WHERE (BH_TaskGuid = T.BH_TaskGuid) AND (BH_UserGuid <> T.BH_AuthorGuid) AND (BH_StartDate >= T.BH_SendDate)) % 60),2)
--), '00:00:00')) AS NonAuthorPlaytimeHours,
FROM bh_historic_report_tasks AS T
INNER JOIN bh_historic_report_users AS Auth
ON ( T.bh_authorguid = Auth.bh_userguid )
LEFT OUTER JOIN bh_historic_report_users AS Sec
ON ( T.bh_completedby = Sec.bh_userguid )
INNER JOIN bh_historic_report_departments AS AuthDept
ON ( T.bh_authordept = AuthDept.bh_departmentguid )
LEFT OUTER JOIN bh_historic_report_departments AS SecDept
ON ( T.bh_completedbydept = SecDept.bh_departmentguid )
INNER JOIN bh_historic_report_workflows AS WF
ON ( T.bh_workflowguid = WF.bh_workflowguid )
LEFT OUTER JOIN (SELECT NULL AS Availability,
A.bh_documenttypeguid,
A.bh_documenttypename,
A.bh_workflowguid,
WF.bh_workflowname,
A.bh_usage
FROM bh_documenttypes AS A
INNER JOIN bh_historic_report_workflows AS WF
ON ( A.bh_workflowguid =
WF.bh_workflowguid )
WHERE ( bh_isglobal = '1'
AND bh_deleted = 0
AND bh_disabled = 0 )
UNION
SELECT DocTypeDept.bh_departmentguid AS Availability,
DOCTYPE.bh_documenttypeguid,
DOCTYPE.bh_documenttypename,
DOCTYPE.bh_workflowguid,
WFLOW.bh_workflowname,
DOCTYPE.bh_usage
FROM bh_documenttypebydepartment AS DOCTYPEDEPT
INNER JOIN bh_documenttypes AS DOCTYPE
ON ( DOCTYPE.bh_documenttypeguid =
DOCTYPEDEPT.bh_documenttypeguid )
LEFT OUTER JOIN bh_historic_report_workflows AS
WFLOW
ON ( DOCTYPE.bh_workflowguid =
WFLOW.bh_workflowguid )
WHERE DOCTYPEDEPT.bh_departmentguid IN
(SELECT DISTINCT tempT.bh_authordept
FROM
bh_historic_report_tasks AS TempT
WHERE
--TempT.BH_SendDate >='20170901'
TempT.bh_completiondate >= #FROMDATE
--Only include tasks sent after a certain date (FORMAT = YYYYMMDD)
AND TempT.bh_completiondate < #TODATE
--Only include tasks sent after a certain date (FORMAT = YYYYMMDD)
)
AND DOCTYPE.bh_deleted = 0
AND DOCTYPE.bh_disabled = 0) AS DT
ON ( T.bh_documenttype = DT.bh_documenttypename )
AND ( ( DT.availability = AuthDept.bh_departmentguid )
OR ( DT.availability IS NULL ) )
AND ( DT.bh_usage = ( CASE
WHEN ( T.bh_source = '15' )
-- Sent from Now client
OR ( T.bh_lengthintenths =
'0'
AND T.bh_source = '18'
)
----OR sent from Hub and zero length
THEN '2' --NOW TYPE
ELSE '1' --VOICE TYPE
END ) )
--Joining on latest Audit row for the task so can return things like the latest Workflow stage etc.
INNER JOIN (SELECT bh_taskguid,
Max(bh_auditid) AS AuditID,
Count(DISTINCT bh_requiredby) RequiredBy,
Count(DISTINCT bh_priorityname) Priorities
FROM bh_historic_report_taskaudit
GROUP BY bh_taskguid) TA
ON T.bh_taskguid = TA.bh_taskguid
INNER JOIN bh_historic_report_taskaudit TAUD
ON TA.auditid = TAUD.bh_auditid
WHERE
--T.BH_CompletionDate IS NOT NULL --Include completed tasks only AND
--T.BH_CompletedByDept IS NOT NULL--Excludes Drafts created but not submitted--changed from--AND SecDept.BH_DepartmentName IS NOT NULL AND
T.bh_completiondate >= #FROMDATE
--Only include tasks created after a certain date (FORMAT = YYYYMMDD)
AND T.bh_completiondate < #TODATE
--Only include tasks created after a certain date (FORMAT = YYYYMMDD)
AND TAUD.bh_startdate >= Dateadd(month, -1, #FROMDATE)
AND TAUD.bh_startdate <= Dateadd(month, 1, #TODATE) --only includes processing audit times for activities started within 1 month prior to and post the Completion Date range
Power BI constructs a query like this:
select * from ( ... your query goes here ... ) as SourceQuery
So when it puts your query between the parenthesis, it isn't a valid query anymore. Power BI does that, because it needs to be able to add joins and filters to your query. Either rebuild the logic inside Power BI using M and DAX, or put your query in a view/UDF in the data source and select from it.

Redshift Optimization

I am looking for some help with optimizing the below. Is there a method if Redshift that can be used to eliminate the need to call the sub select each time since they are virtually the same for different fields:
select
IdText AS EquipmentPointCode,
OnRLT AS Downtime,
( SELECT OnRLT FROM temp_pointsvr_uptime_dataset WHERE IdText = (select IDtext from list_of_ids where rownum =1) AND OnRLT > t1.OnRLT ORDER BY OnRLT ASC LIMIT 1) AS Uptime,
( SELECT LineDefault_Value1 FROM temp_not_pointsvr_downtime WHERE IdText = (select IDtext from list_of_ids where rownum =1) AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS LineDefault_Value1,
( SELECT LineDefault_Value2 FROM temp_not_pointsvr_downtime WHERE IdText = (select IDtext from list_of_ids where rownum =1) AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS LineDefault_Value2,
( SELECT LineDefault_Value3 FROM temp_not_pointsvr_downtime WHERE IdText = (select IDtext from list_of_ids where rownum =1) AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS LineDefault_Value3,
( SELECT LineDefault_Value4 FROM temp_not_pointsvr_downtime WHERE IdText = (select IDtext from list_of_ids where rownum =1) AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS LineDefault_Value4,
( SELECT LineDefault_Value5 FROM temp_not_pointsvr_downtime WHERE IdText = (select IDtext from list_of_ids where rownum =1) AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS LineDefault_Value5,
( SELECT LineDefault_Value6 FROM temp_not_pointsvr_downtime WHERE IdText = (select IDtext from list_of_ids where rownum =1) AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS LineDefault_Value6,
( SELECT LineDefault_Value7 FROM temp_not_pointsvr_downtime WHERE IdText = (select IDtext from list_of_ids where rownum =1) AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS LineDefault_Value7,
( SELECT StateDefault_Value1 FROM temp_not_pointsvr_downtime WHERE IdText = (select IDtext from list_of_ids where rownum =1) AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS StateDefault_Value1,
( SELECT StateDefault_Value2 FROM temp_not_pointsvr_downtime WHERE IdText = (select IDtext from list_of_ids where rownum =1) AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS StateDefault_Value2,
( SELECT StateDefault_Value3 FROM temp_not_pointsvr_downtime WHERE IdText = (select IDtext from list_of_ids where rownum =1) AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS StateDefault_Value3,
'FM 10' AS Equipment
FROM temp_pointsvr_downtime t1
WHERE IdText = (select IDtext from list_of_ids where rownum =1)
I feel like what you're trying to do can be accomplished using case statements, but without seeing an example of the tables/data you're working with it's tough to determine.
Tackling just the nested select statements, you should be able to use a common table expression to hit the table one time, instead of re-selecting from it each time:
WITH
id_text_filter AS (
SELECT IDtext
FROM list_of_ids
WHERE rownum = 1
)
SELECT
IdText AS EquipmentPointCode,
OnRLT AS Downtime,
( SELECT OnRLT FROM temp_pointsvr_uptime_dataset WHERE IdText = (select IDtext from list_of_ids where rownum =1) AND OnRLT > t1.OnRLT ORDER BY OnRLT ASC LIMIT 1) AS Uptime,
( SELECT LineDefault_Value1 FROM temp_not_pointsvr_downtime WHERE ti.IdText = f.IDtext AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS LineDefault_Value1,
( SELECT LineDefault_Value2 FROM temp_not_pointsvr_downtime WHERE ti.IdText = f.IDtext AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS LineDefault_Value2,
( SELECT LineDefault_Value3 FROM temp_not_pointsvr_downtime WHERE ti.IdText = f.IDtext AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS LineDefault_Value3,
( SELECT LineDefault_Value4 FROM temp_not_pointsvr_downtime WHERE ti.IdText = f.IDtext AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS LineDefault_Value4,
( SELECT LineDefault_Value5 FROM temp_not_pointsvr_downtime WHERE ti.IdText = f.IDtext AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS LineDefault_Value5,
( SELECT LineDefault_Value6 FROM temp_not_pointsvr_downtime WHERE ti.IdText = f.IDtext AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS LineDefault_Value6,
( SELECT LineDefault_Value7 FROM temp_not_pointsvr_downtime WHERE ti.IdText = f.IDtext AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS LineDefault_Value7,
( SELECT StateDefault_Value1 FROM temp_not_pointsvr_downtime WHERE ti.IdText = f.IDtext AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS StateDefault_Value1,
( SELECT StateDefault_Value2 FROM temp_not_pointsvr_downtime WHERE ti.IdText = f.IDtext AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS StateDefault_Value2,
( SELECT StateDefault_Value3 FROM temp_not_pointsvr_downtime WHERE ti.IdText = f.IDtext AND OffRLT = t1.OnRLT ORDER BY ResetRLT DESC Limit 1) AS StateDefault_Value3,
'FM 10' AS Equipment
FROM temp_pointsvr_downtime t1
JOIN id_text_filter f ON ti.IDtext = f.IDtext
WHERE IdText = (SELECT IDtext FROM list_of_ids WHERE rownum =1)
Again, I'm not sure if this code will work straight out of the box, as I'm not able to test it. But the idea should be similar:
1) Create a common table expression with the data you want to use as a filter
2) Join to that table in the main SELECT
3) Define WHERE clauses based on an equality to the common table expression.

How can I insert the result of 3 select statements on 3 tables into a new table in Hive?

select sum(column_table1) from table1 where job_run_time_stamp >= '2016-12-15 00:00:00' and job_run_time_stamp < '2016-12-16 00:00:00';
select sum(column_table2) from table2 where job_run_time_stamp >= '2016-12-15 00:00:00' and job_run_time_stamp < '2016-12-16 00:00:00';
select sum(column_table3) from table3 where job_run_time_stamp >= '2016-12-15 00:00:00' and job_run_time_stamp < '2016-12-16 00:00:00';
How can I combine the above 3 query results and put them into a 4th table (as 3 different columns) called table4 in Hive?
Following can work
insert into table4
values(
select sum(t.sum1) , sum(t.sum2), sum(t.sum3) from
(select sum(column_table1) as sum1 , 0 as sum2, 0 as sum3 from table1 where job_run_time_stamp >= '2016-12-15 00:00:00' and job_run_time_stamp < '2016-12-16 00:00:00'
union
select 0, sum(column_table2) , 0 from table2 where job_run_time_stamp >= '2016-12-15 00:00:00' and job_run_time_stamp < '2016-12-16 00:00:00'
union
select 0,0, sum(column_table3) from table3 where job_run_time_stamp >= '2016-12-15 00:00:00' and job_run_time_stamp < '2016-12-16 00:00:00') as t
)

Optimize MySQl Query (Substitution from Column Level query)

I have Following MySQL Query.How can I optimize this.
Basically what this query is doing .
I have two different table for employee and his pay history, I need to show the sum of national insurance contribution for each employee and for each month as column.
I am able to acheive this functionality but I dont think the approach is right.How can I modify this statement in light of performance.
DECLARE firstStartDate DATETIME;
SET firstStartDate = GetFirstPeriodStartDateForFiscalYear(iGroupID,iFiscalYear);
SELECT
(SELECT fullname) as 'Employee Name',
(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(firstStartDate)=MONTHNAME(PeriodEndDate)) as 'Mon1',
(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 1 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon2' ,
(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 2 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon3' ,
(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 3 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon4' ,
(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 4 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon5' ,
(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 5 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon6' ,
(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 6 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon7' ,
(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 7 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon8' ,
(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 8 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon9' ,
(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 9 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon10' ,
(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 10 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon11' ,
(SELECT SUM(EE_NI_Contrib)
FROM eepayhistory
WHERE eepayhistory.employee_id = Employee.pkEmpid
AND MONTHNAME(DATE_ADD(firstStartDate, INTERVAL 11 MONTH) )=MONTHNAME(PeriodEndDate)) as 'Mon12'
FROM Employee
LEFT OUTER JOIN eepayhistory
ON eepayhistory.employee_id = Employee.pkEmpid
AND Employee.CompanyId = iCompanyID
Group by 'Employee Name';
How can I optimize this query.