I have select, iside select have 2 column. This column must be filled from same select, but I don't want use select twice for it. Is it possoble use select 1 time and after that set second column value from first?
Example:
insert into #temptable from
select
a = (select aa from table1 where quantity > 5)
b = (select aa from table1 where quantity > 5)
I need:
insert into #temptable from
select
a = (select aa from table1 where quantity > 5)
b = {value from a}
Update. I wrote bad example, I need set to BalancePrediction1 and BalancePrediction2 value from Balance
INSERT #tmpBalances
SELECT PA.ContractId AS 'ContractId',
Con.Name AS 'ContractName',
Bal.PortfolioAccountId AS 'PortfolioAccountId',
PA.Name AS 'PortfolioAccountName',
RA.GeneralId AS 'RegisterAccountGeneralId',
Bal.BalanceTypeId AS 'BalanceTypeId',
Bt.Name AS 'BalanceTypeName',
Bt.Type AS 'BalanceTypeType',
Bal.BalanceTimeType AS 'BalanceTimeType',
Bal.InstrumentId AS 'InstrumentId',
Ins.Name AS 'InstrumentName',
Ins.GeneralId AS 'InstrumentGeneralId',
(Bal.Balance -
(
SELECT COALESCE(SUM(Mov.Amount), 0)
FROM trd.Movements AS Mov
WHERE
Bal.InstrumentId = Mov.InstrumentId AND
Bal.PortfolioAccountId = Mov.PortfolioAccountId AND
Bal.BalanceTypeId = Mov.BalanceTypeId AND
Bal.BalanceTimeType = Mov.BalanceTimeType AND
DateDiff(DAY, #Date, Mov.Date) > 0 AND
-- Currency může být null a NULL = NULL nejde
COALESCE(Bal.CurrencyId, -1) = COALESCE(Mov.CurrencyId, -1)
)
) as Balance,
Balance AS 'BalancePrediction1',
Balance AS 'BalancePrediction2',
Bal.CurrencyId AS 'CurrencyId',
Ccy.Code AS 'CurrencyCode',
PA.PositionServiceType 'PositionServiceType',
Ccy.Name 'CurrencyName',
S.Nominal AS 'Nominal',
S.NominalCurrencyId AS 'NominalCurrencyId',
trd.GetCurrencyCode(S.NominalCurrencyId) AS 'NominalCurrencyCode'
FROM trd.Balances AS Bal
JOIN trd.PortfolioAccounts AS PA ON PA.Id = Bal.PortfolioAccountId
JOIN trd.Contracts AS Con ON Con.Id = PA.ContractId
JOIN trd.RegisterAccounts AS RA ON RA.Id = PA.RegisterAccountId
JOIN trd.BalanceTypes AS Bt ON Bt.Id = Bal.BalanceTypeId
JOIN trd.Instruments AS Ins ON Ins.Id = Bal.InstrumentId
LEFT OUTER JOIN trd.Currencies AS Ccy ON Ccy.Id = Bal.CurrencyId
LEFT JOIN trd.SecuritiesView S ON s.Id = Ins.Id AND DateDiff(d, S.ValidFrom, #Date) >= 0 AND (S.ValidTo IS NULL OR DateDiff(d, S.ValidTo, #Date) < 0)
AND S.InstrumentInstrumentTypePriceUnit = 1
You could do an update to the table variable after the insert.
update #tmpBalances
set BalancePrediction1 = Balance,
BalancePrediction2 = Balance
Or you can use cross apply to calculate the sum.
INSERT #tmpBalances
SELECT PA.ContractId AS 'ContractId',
Con.Name AS 'ContractName',
Bal.PortfolioAccountId AS 'PortfolioAccountId',
PA.Name AS 'PortfolioAccountName',
RA.GeneralId AS 'RegisterAccountGeneralId',
Bal.BalanceTypeId AS 'BalanceTypeId',
Bt.Name AS 'BalanceTypeName',
Bt.Type AS 'BalanceTypeType',
Bal.BalanceTimeType AS 'BalanceTimeType',
Bal.InstrumentId AS 'InstrumentId',
Ins.Name AS 'InstrumentName',
Ins.GeneralId AS 'InstrumentGeneralId',
(Bal.Balance - Mov.SumAmount) AS Balance,
(Bal.Balance - Mov.SumAmount) AS 'BalancePrediction1',
(Bal.Balance - Mov.SumAmount) AS 'BalancePrediction2',
Bal.CurrencyId AS 'CurrencyId',
Ccy.Code AS 'CurrencyCode',
PA.PositionServiceType 'PositionServiceType',
Ccy.Name 'CurrencyName',
S.Nominal AS 'Nominal',
S.NominalCurrencyId AS 'NominalCurrencyId',
trd.GetCurrencyCode(S.NominalCurrencyId) AS 'NominalCurrencyCode'
FROM trd.Balances AS Bal
JOIN trd.PortfolioAccounts AS PA ON PA.Id = Bal.PortfolioAccountId
JOIN trd.Contracts AS Con ON Con.Id = PA.ContractId
JOIN trd.RegisterAccounts AS RA ON RA.Id = PA.RegisterAccountId
JOIN trd.BalanceTypes AS Bt ON Bt.Id = Bal.BalanceTypeId
JOIN trd.Instruments AS Ins ON Ins.Id = Bal.InstrumentId
LEFT OUTER JOIN trd.Currencies AS Ccy ON Ccy.Id = Bal.CurrencyId
LEFT JOIN trd.SecuritiesView S ON s.Id = Ins.Id AND DateDiff(d, S.ValidFrom, #Date) >= 0 AND (S.ValidTo IS NULL OR DateDiff(d, S.ValidTo, #Date) < 0)
AND S.InstrumentInstrumentTypePriceUnit = 1
CROSS APPLY (SELECT COALESCE(SUM(Mov.Amount), 0)
FROM trd.Movements AS Mov
WHERE
Bal.InstrumentId = Mov.InstrumentId AND
Bal.PortfolioAccountId = Mov.PortfolioAccountId AND
Bal.BalanceTypeId = Mov.BalanceTypeId AND
Bal.BalanceTimeType = Mov.BalanceTimeType AND
DateDiff(DAY, #Date, Mov.Date) > 0 AND
-- Currency může být null a NULL = NULL nejde
COALESCE(Bal.CurrencyId, -1) = COALESCE(Mov.CurrencyId, -1)
) Mov(SumAmount)
SELECT aa AS a, aa AS b
FROM table1
WHERE quantity > 5
One way;
;with T (value) as (
select aa from table1 where quantity > 5
)
insert into #temptable
select value, value from T
Related
I have an select:
SELECT
tb_dim_equipe.no_equipe "EQUIPE",
tb_dim_profissional.no_profissional "PROFISSIONAL",
no_cidadao "CIDADÃO",
a.nu_cns "CNS",
sum(case when co_dim_tempo >= 20190100 and co_dim_tempo <= 20200131 then 1 else 0 end) as "TOTAL"
from (
SELECT no_cidadao,
tb_fat_cad_individual.nu_cns,
tb_fat_cad_individual.co_dim_profissional,
tb_fat_cad_individual.co_dim_equipe from tb_fat_cidadao_pec
join tb_fat_cad_individual on tb_fat_cad_individual.nu_cns = tb_fat_cidadao_pec.nu_cns
join tb_fat_cidadao on tb_fat_cad_individual.co_seq_fat_cad_individual = tb_fat_cidadao.co_fat_cad_individual
where st_mudou = 0
and st_vivo = 1
and st_gestante = 1
and tb_fat_cidadao.co_dim_tempo_validade = 30001231) a
left join (
SELECT tb_fat_atendimento_individual.nu_cns,
tb_fat_atendimento_individual.co_dim_tempo
from tb_fat_atendimento_individual
join tb_dim_tempo on tb_dim_tempo.co_seq_dim_tempo = tb_fat_atendimento_individual.co_dim_tempo
where co_seq_dim_tempo >= 20190100
and co_seq_dim_tempo <= 20200131
and ds_filtro_ciaps like '%ABP001%'
union SELECT tb_fat_proced_atend.nu_cns,
tb_fat_proced_atend.co_dim_tempo
from tb_fat_proced_atend
join tb_dim_tempo on tb_dim_tempo.co_seq_dim_tempo = tb_fat_proced_atend.co_dim_tempo
where co_seq_dim_tempo >= 20190100
and co_seq_dim_tempo <= 20200131
and ds_filtro_procedimento like '%0301010110%') b
on a.nu_cns = b.nu_cns
join tb_dim_equipe on tb_dim_equipe.co_seq_dim_equipe = a.co_dim_equipe
join tb_dim_profissional on tb_dim_profissional.co_seq_dim_profissional = a.co_dim_profissional
group by no_equipe, no_profissional, no_cidadao, a.nu_cns
order by no_equipe, no_profissional, no_cidadao
This return to me five columns EQUIPE, PROFISSIONAL, CIDADÃO, CNS and TOTAL
I want to create a new select command like this:
SELECT sum(c.TOTAL) from *query above* c
but I receive the error that column not exists.
How I can use a select with the names of alias columns EQUIPE, PROFISSIONAL, CIDADÃO, CNS and TOTAL?
Just like in the alias, you need to quote the column identifier if it is all-uppercase:
SELECT sum(c."TOTAL") from /*query above*/ c
-- ^ ^
How can I find what was the available stock on a specific date in the past?
I know how to get OnHand for any date in the past:
SELECT LocType, LocCode, ItemCode, SUM(InQty-OutQty) [OnHand]
From OIVL
Where DocDate <= '7/7/2017'
AND ITEMCODE = 'xyz'
Group by LocType, LocCode, ItemCode
But this does not account for what was committed. It shows what was on hand, but not what was actually available (OnHand - Committed = Available). So, how could I get to this "Available" number for dates in the past?
Thanks!
In case this helps anyone else.... here is an example of how to get your item quantity and cost history in SAP BusinessOne. Pass the date and item you want to see history for into the function. If you omit item code it returns all items.
CREATE FUNCTION [dbo].[ufnStockAndCostHistory]
(
#EndDate DATETIME, #ItemCode NVARCHAR(255) = 'All'
)
RETURNS TABLE
AS
RETURN
(
WITH Cost AS (
SELECT
OINM.TransNum,
OINM.ItemCode,
OINM.Warehouse,
OINM.Balance,
OINM.CreateDate
FROM OINM (NOLOCK)
JOIN OITM (NOLOCK) ON OITM.ItemCode = OINM.ItemCode
JOIN OITB (NOLOCK) ON OITM.ItmsGrpCod=OITB.ItmsGrpCod
WHERE OINM.CreateDate <= #EndDate
),
FinalCostByWarehouse AS (
SELECT *
FROM Cost
WHERE TransNum = (
SELECT MAX(TransNum)
FROM Cost sub
WHERE Cost.ItemCode = sub.ItemCode
AND Cost.Warehouse = sub.Warehouse)
),
Quantity AS (
SELECT
OINM.ItemCode,
OINM.Warehouse,
SUM(OINM.InQty) - SUM(OINM.OutQty) [Qty]
FROM OINM (NOLOCK)
JOIN OITM (NOLOCK) ON OITM.ItemCode = OINM.ItemCode
JOIN OITB (NOLOCK) ON OITM.ItmsGrpCod=OITB.ItmsGrpCod
WHERE OINM.CreateDate <= #EndDate
group by OINM.ItemCode, OINM.Warehouse
)
SELECT
OITW.ItemCode,
OITW.WhsCode,
c.Balance [Cost],
q.Qty [Quantity]
FROM OITW
LEFT JOIN FinalCostByWarehouse c ON OITW.ItemCode = c.ItemCode
AND OITW.WhsCode = c.Warehouse
LEFT JOIN Quantity q ON OITW.ItemCode = q.ItemCode
AND OITW.WhsCode = q.Warehouse
WHERE (OITW.ItemCode = #ItemCode
OR #ItemCode = 'All')
AND (ISNULL(c.Balance,0) > 0
OR ISNULL(q.Qty,0) > 0)
)
Usage would look like:
SELECT *
FROM ufnStockAndCostHistory('9/15/2017','B107A-12HB')
I've created a TSQL query that pulls from two sets of tables in my database. The tables in the Common Table Expression are different from the tables in the main query. I'm joining on MRN and need the end result to contain accounts from both sets of tables. I've written the following query to this end:
with cteHosp as(
select Distinct p.EncounterNumber, p.MRN, p.AdmitAge
from HospitalPatients p
inner join Eligibility e on p.MRN = e.MRN
inner join HospChgDtl c on p.pt_id = c.pt_id
inner join HospitalDiagnoses d on p.pt_id = d.pt_id
where p.AdmitAge >=12
and d.dx_cd in ('G89.4','R52.1','R52.2','Z00.129')
)
Select Distinct a.AccountNo, a.dob, DATEDIFF(yy, a.dob, GETDATE()) as Age
from RHCCPTDetail c
inner join RHCAppointments a on c.ClaimID = a.ClaimID
inner join Eligibility e on c.hl7Id = e.MRN
full outer join cteHosp on e.MRN = cteHosp.MRN
where DATEDIFF(yy, a.dob, getdate()) >= 12
and left(c.PriDiag,7) in ('G89.4','R52.1','R52.2', 'Z00.129')
or (
DATEDIFF(yy, a.dob, getdate()) >= 12
and LEFT(c.DiagCode2,7) in ('G89.4','R52.1','R52.2','Z00.129')
)
or (
DATEDIFF(yy, a.dob, getdate()) >= 12
and LEFT(c.DiagCode3,7) in ('G89.4','R52.1','R52.2','Z00.129')
)
or (
DATEDIFF(yy, a.dob, getdate()) >= 12
and LEFT(c.DiagCode4,7) in ('G89.4','R52.1','R52.2','Z00.129')
)
order by AccountNo
How do I merge together the output of both the common table expression and the main query into one set of results?
Merge performs inserts, updates or deletes. I believe you want to join the cte. If so, here is an example.
Notice the cteBatch is joined to the Main query below.
with
cteBatch (BatchID,BatchDate,Creator,LogID)
as
(
select
BatchID
,dateadd(day,right(BatchID,3) -1,
cast(cast(left(BatchID,4) as varchar(4))
+ '-01-01' as date)) BatchDate
,Creator
,LogID
from tblPriceMatrixBatch b
unpivot
(
LogID
for Logs in (LogIDISI,LogIDTG,LogIDWeb)
)u
)
Select
0 as isCurrent
,i.InterfaceID
,i.InterfaceName
,b.BatchID
,b.BatchDate
,case when isdate(l.start) = 0 and isdate(l.[end]) = 0 then 'Scheduled'
when isdate(l.start) = 1 and isdate(l.[end]) = 0 then 'Running'
when isdate(l.start) = 1 and isdate(l.[end]) = 1 and isnull(l.haserror,0) = 1 then 'Failed'
when isdate(l.start) = 1 and isdate(l.[end]) = 1 and isnull(l.haserror,0) != 1 then 'Success'
else 'idunno' end as stat
,l.Start as StartTime
,l.[end] as CompleteTime
,b.Creator as Usr
from EOCSupport.dbo.Interfaces i
join EOCSupport.dbo.Logs l
on i.InterfaceID = l.InterfaceID
join cteBatch b
on b.logid = l.LogID
In this query I cant understand what would be the proper syntax to PIVOT it by month and also display just top 10 records based on SUM(NetWrittenPremium).
;with cte_TopClasses
AS (
select
b.YearNum,
b.MonthNum,
REPLACE(ClassCode,'+','') + ' - '+ QLL.Description as Description,
SUM( Premium) as NetWrittenPremium
FROM tblCalendar b
LEFT JOIN ProductionReportMetrics prm ON b.MonthNum=Month(prm.EffectiveDate) AND b.YearNum = YEAR(EffectiveDate)
AND prm.EffectiveDate >=DateAdd(yy, -1, DATEADD(d, 1, EOMONTH(GETDATE()))) AND prm.EffectiveDate <= EOMONTH(GETDATE()) AND CompanyLine = 'Ironshore Insurance Company'
LEFT JOIN NetRate_Quote_Insur_Quote Q ON prm.NetRate_QuoteID = Q.QuoteID
LEFT JOIN NetRate_Quote_Insur_Quote_Locat QL ON Q.QuoteID = QL.QuoteID
LEFT JOIN (SELECT * FROM NetRate_Quote_Insur_Quote_Locat_Liabi nqI
JOIN ( SELECT LocationID as LocID, MAX(ClassCode) as ClCode
FROM NetRate_Quote_Insur_Quote_Locat_Liabi GROUP BY LocationID ) nqA
ON nqA.LocID = nqI.LocationID AND nqA.ClCode = nqI.ClassCode ) QLL
ON QLL.LocationID = QL.LocationID
WHERE ( b.YearNum = YEAR(GETDATE())-1 and b.MonthNum >= MONTH(GETDATE())+1 ) OR
( b.YearNum = YEAR(GETDATE()) and b.MonthNum <= MONTH(GETDATE()) )
GROUP BY b.YearNum,b.MonthNum,ClassCode, QLL.Description
)
SELECT
--TOP 10
RANK() OVER (ORDER BY NetWrittenPremium DESC) AS Rank, *
FROM cte_TopClasses
WHERE Description IS NOT NULL
ORDER BY NetWrittenPremium DESC,YearNum,MonthNum
The result should look something like that:
If I use the query below and then using matrics in SSRS to PIVOT it - then after grouping by Description it only displays me 2 Description.
;with cte_TopClasses
AS (
select
b.YearNum,
b.MonthNum,
REPLACE(ClassCode,'+','') + ' - '+ QLL.Description as Description,
SUM( Premium) as NetWrittenPremium
FROM tblCalendar b
LEFT JOIN ProductionReportMetrics prm ON b.MonthNum=Month(prm.EffectiveDate) AND b.YearNum = YEAR(EffectiveDate)
AND prm.EffectiveDate >=DateAdd(yy, -1, DATEADD(d, 1, EOMONTH(GETDATE()))) AND prm.EffectiveDate <= EOMONTH(GETDATE()) AND CompanyLine = 'Ironshore Insurance Company'
LEFT JOIN NetRate_Quote_Insur_Quote Q ON prm.NetRate_QuoteID = Q.QuoteID
LEFT JOIN NetRate_Quote_Insur_Quote_Locat QL ON Q.QuoteID = QL.QuoteID
LEFT JOIN (SELECT * FROM NetRate_Quote_Insur_Quote_Locat_Liabi nqI
JOIN ( SELECT LocationID as LocID, MAX(ClassCode) as ClCode
FROM NetRate_Quote_Insur_Quote_Locat_Liabi GROUP BY LocationID ) nqA
ON nqA.LocID = nqI.LocationID AND nqA.ClCode = nqI.ClassCode ) QLL
ON QLL.LocationID = QL.LocationID
WHERE ( b.YearNum = YEAR(GETDATE())-1 and b.MonthNum >= MONTH(GETDATE())+1 ) OR
( b.YearNum = YEAR(GETDATE()) and b.MonthNum <= MONTH(GETDATE()) )
GROUP BY b.YearNum,b.MonthNum,ClassCode, QLL.Description
)
SELECT *
FROM (SELECT RANK() OVER (ORDER BY NetWrittenPremium DESC) AS Rank, *
FROM cte_TopClasses
WHERE Description IS NOT NULL) AA
WHERE AA.Rank <= 10
ORDER BY AA.NetWrittenPremium DESC, AA.YearNum, AA.MonthNum
And the result of it in SSRS matrics :
You could try something like this at the end of the query, rather than what is there now:
SELECT *
FROM (SELECT RANK() OVER (ORDER BY [Description] DESC) AS Rank, *
FROM cte_TopClasses
WHERE Description IN (SELECT [Description]
FROM (SELECT RANK() OVER (ORDER BY SUM(NetWrittenPremium) DESC) AS [Rank], [Description], SUM(NetWrittenPremium) AS total
FROM cte_TopClasses
WHERE [Description] IS NOT NULL
GROUP BY [Description]) BB
WHERE [Rank] <= 10)) AA
ORDER BY YearNum, MonthNum
This wraps the query in a SELECT, and filters the ranked results to the 10 you want.
Then use a matrix in the report to pivot the results.
I have the following SQL query on IBM DB2.
SUM(CASE
WHEN verzijaplaca.vpl_vrsteplacila = 9150 THEN
(select sum(verplaca.vpl_bruto)
from pet320.verzijaplaca as verplaca
)
ELSE 0
END) AS "brutoplacazaure"
The inner select works, but when I include it in CASE when it reports error.
ERROR: An operand of a column function is invalid.
DB2 SQL Error:
SQLCODE=-112, SQLSTATE=42607, SQLERRMC=null, DRIVER=3.57.91
Error
Code: -112
Also If I run only
SUM(CASE
WHEN verzijaplaca.vpl_vrsteplacila = 9150 THEN
(1.0)
ELSE 0
END) AS "brutoplacazaure"
it works
Any suggestions?? It seems that DB 2 doesn't support the inner sql in case when case or smth like that
Thank you
the whole sql query is the following
SELECT
zaposleni.za_koda AS "za_koda",
MAX(enotezpiz.ezp_rsza) AS "ezp_rsza",
MAX(zaposleni.za_polnoime) AS "za_polnoime",
MAX(verzije.ve_datnamena) AS "ve_datnamena",
MAX(verzije.ve_datizp) AS "ve_datizp",
MAX(opp_telefonodgos) AS "opp_telefonodgos",
MAX(pod_krajzaizpise ||', ') AS "pod_krajzaizpise",
MAX(racuni.ra_stracuna) AS "ra_stracuna",
MAX(racuni.ra_modul) AS "ra_modul",
MAX(racuni.ra_sklstev) AS "ra_sklstev",
MAX(verzije.ve_datizp) AS "ve_datizp",
MAX(verzije.ve_naziv) AS "ve_naziv",
SUM(CASE
WHEN vrsteplacila.vp_skupinevrpl in (1,2,3,4,16) and vrsteplacila.vp_udodatkov = 0 THEN verzijaplaca.vpl_eure
ELSE 0
END) AS "mfure",
MAX(dmzaposlenih.dmz_enotezpiz) AS "dmz_enotezpiz",
(select
SUM(olajsave.ozz_znesekolajsave) / 12
from
pet320.olajsavedczaposlenih as olajsave
INNER JOIN
pet320.verzije as verzija1
ON
olajsave.ooz_datumod <= verzija1.ve_datkm AND (olajsave.ooz_datumdo IS NULL OR olajsave.ooz_datumdo >= verzija1.ve_datzm)
INNER JOIN
pet320.zaposleni as zapp
ON
olajsave.ozz_zaposleni = zapp.za_id_za
INNER JOIN
pet320.VERZIJAPLACA as vpl
ON
vpl.vpl_verzije = verzija1.ve_id_ve
AND zapp.za_id_za = vpl.vpl_zaposleni
where
1=1
AND (vpl.vpl_vrsteplacila = 9150 OR vpl.vpl_skupinevrpl = 6)) AS "vz_znesvzddc",
SUM(CASE
WHEN vrsteplacila.vp_skupinevrpl = 3 AND vrsteplacila.vp_udodatkov = 0 THEN verzijaplaca.vpl_eure
WHEN vrsteplacila.vp_skupinevrpl = 4 AND vrsteplacila.vp_udodatkov = 1 THEN verzijaplaca.vpl_eure
ELSE
0
END) AS "bolovalure",
SUM(CASE
WHEN vrsteplacila.vp_skupinevrpl = 4 AND vrsteplacila.vp_udodatkov = 0 THEN verzijaplaca.vpl_eure
ELSE
0
END) AS "izostanekzdelaure",
SUM(CASE
WHEN vrsteplacila.vp_skupinevrpl = 3 THEN verzijaplaca.vpl_bruto
ELSE
0
END) AS "brutoznesekboleznine",
SUM(CASE WHEN vrsteplacila.vp_skupinevrpl = 16 THEN verzijaplaca.vpl_bruto
ELSE
0
END) AS "brutodopolnega",
SUM(CASE WHEN vrsteplacila.vp_skupinevrpl = 16 and vrsteplacila.vp_udodatkov = 0 THEN verzijaplaca.vpl_eure
ELSE
0
END) AS "uredopolenga",
SUM(CASE
WHEN vrsteplacila.vp_skupinevrpl IN (16) THEN (verzijaplaca.vpl_bruto - verzijaplaca.vpl_neto)
ELSE
0
END) AS "prispevkizasocvarnost",
SUM(CASE
WHEN vrsteplacila.vp_skupinevrpl IN (16) THEN verzijaplaca.vpl_akdohod
ELSE
0
END) AS "akdohodnine",
SUM(CASE
WHEN verzijaplaca.vpl_skupinevrpl IN (16) THEN verzijaplaca.vpl_neto - verzijaplaca.vpl_akdohod
ELSE
0
END) AS "netonadomestilo",
SUM(CASE WHEN verzijaplaca.vpl_vrsteplacila = 9150 THEN
(select sum(verplaca.vpl_bruto)
from pet320.verzijaplaca as verplaca
INNER JOIN
pet320.verzije as ver
ON
ver.ve_id_ve = verplaca.vpl_verzije
INNER JOIN
pet320.zaposleni as zapo
ON
zapo.za_id_za = verplaca.vpl_zaposleni
AND ver.ve_id_ve = verplaca.vpl_verzije
where verplaca.vpl_vrsteplacila in (select vp_id_vp from pet320.vrsteplacila where vp_skupinevrpl in (1,2))
and verplaca.vpl_zaposleni = zapo.za_id_za
and verplaca.vpl_verzije = ver.ve_id_ve)
ELSE 0
END) AS "brutoplacazaure"
FROM
pet320.verzijaplaca AS verzijaplaca
INNER JOIN
pet320.vrsteplacila AS vrsteplacila
ON
verzijaplaca.vpl_vrsteplacila = vrsteplacila.vp_id_vp
INNER JOIN
pet320.verzije AS verzije
ON
verzijaplaca.vpl_verzije = verzije.ve_id_ve
INNER JOIN
pet320.zaposleni AS zaposleni
ON
verzijaplaca.vpl_zaposleni = zaposleni.za_id_za
INNER JOIN
(SELECT
a.*
FROM
pet320.dmzaposlenih AS a
INNER JOIN
(SELECT
dmz_zaposleni,
MAX(dmz_datumod) AS max_dmz_datumod
FROM
pet320.dmzaposlenih
GROUP BY
dmz_zaposleni) AS b
ON
a.dmz_zaposleni = b.dmz_zaposleni
AND a.dmz_datumod = b.max_dmz_datumod) as dmzaposlenih
ON
dmzaposlenih.dmz_zaposleni = verzijaplaca.vpl_zaposleni
INNER JOIN
pet320.enotezpiz AS enotezpiz
ON
dmzaposlenih.dmz_enotezpiz = enotezpiz.ezp_id_ezp
LEFT JOIN
pet320.osnovnipodplace AS osnovnipodplace
ON
1=1
INNER JOIN
pet320.racuni AS racuni
ON
osnovnipodplace.opp_racuni = racuni.ra_id_ra
INNER JOIN
pet320.podjetja AS podjetja
ON
osnovnipodplace.opp_podjetja = podjetja.pod_id_pod
LEFT JOIN
pet320.verzijazaposleni AS verzijazaposleni
ON
verzijazaposleni.vz_zaposleni = zaposleni.za_id_za
AND verzijazaposleni.vz_verzije = verzije.ve_id_ve
INNER JOIN
pet320.verzijastrmesta as verzijastrmesta
ON
verzijastrmesta.vs_verzije = verzije.ve_id_ve
AND verzijastrmesta.vs_strmesta = dmzaposlenih.dmz_strmesta
INNER JOIN
pet320.verzijaorgenote AS verzijaorgenote
ON
verzijaorgenote.vo_verzije = verzije.ve_id_ve
AND verzijaorgenote.vo_orgenote = dmzaposlenih.dmz_orgenote
INNER JOIN
pet320.zaposinvalidi AS zaposinvalidi
ON
zaposinvalidi.zi_zaposleni = verzijaplaca.vpl_zaposleni and zi_datdo is null
INNER JOIN
pet320.verzijasumstavki AS verzijasumstavki
ON
verzijasumstavki.vss_verzije = verzijaplaca.vpl_verzije AND
verzijasumstavki.vss_zaposleni = verzijaplaca.vpl_zaposleni AND
verzijasumstavki.vss_vrsteplacila = 9301
WHERE
1=1
AND vrsteplacila.vp_skupinevrpl in (1,2,3,4,16)
AND (verzijaplaca.vpl_verzije = 215)
AND (verzijaplaca.vpl_zaposleni IS NULL OR 1=1)
AND (verzijaplaca.vpl_strm_strmesta IS NULL OR 1=1)
AND (dmzaposlenih.dmz_orgenote IS NULL OR 1=1)
AND (dmzaposlenih.dmz_izplacilnamesta IS NULL OR 1=1)
AND (verzijaplaca.vpl_placilnirazredi IS NULL OR 1=1)
AND (dmzaposlenih.dmz_vrstapog IN (1,0))
AND verzijaplaca.vpl_zaposleni in (select distinct vpl_zaposleni from pet320.verzijaplaca where vpl_skupinevrpl = 16 AND vpl_verzije = 215)
group by dmzaposlenih.dmz_enotezpiz,
zaposleni.za_koda
ORDER BY
dmzaposlenih.dmz_enotezpiz,
zaposleni.za_koda
INNER JOIN
(SELECT
a.*
FROM
pet320.dmzaposlenih AS a
INNER JOIN
(SELECT
dmz_zaposleni,
MAX(dmz_datumod) AS max_dmz_datumod
FROM
pet320.dmzaposlenih
GROUP BY
dmz_zaposleni) AS b
ON
a.dmz_zaposleni = b.dmz_zaposleni
AND a.dmz_datumod = b.max_dmz_datumod) as dmzaposlenih
ON
dmzaposlenih.dmz_zaposleni = verzijaplaca.vpl_zaposleni
INNER JOIN
pet320.enotezpiz AS enotezpiz
ON
dmzaposlenih.dmz_enotezpiz = enotezpiz.ezp_id_ezp
LEFT JOIN
pet320.osnovnipodplace AS osnovnipodplace
ON
1=1
INNER JOIN
pet320.racuni AS racuni
ON
osnovnipodplace.opp_racuni = racuni.ra_id_ra
INNER JOIN
pet320.podjetja AS podjetja
ON
osnovnipodplace.opp_podjetja = podjetja.pod_id_pod
LEFT JOIN
pet320.verzijazaposleni AS verzijazaposleni
ON
verzijazaposleni.vz_zaposleni = zaposleni.za_id_za
AND verzijazaposleni.vz_verzije = verzije.ve_id_ve
INNER JOIN
pet320.verzijastrmesta as verzijastrmesta
ON
verzijastrmesta.vs_verzije = verzije.ve_id_ve
AND verzijastrmesta.vs_strmesta = dmzaposlenih.dmz_strmesta
INNER JOIN
pet320.verzijaorgenote AS verzijaorgenote
ON
verzijaorgenote.vo_verzije = verzije.ve_id_ve
AND verzijaorgenote.vo_orgenote = dmzaposlenih.dmz_orgenote
INNER JOIN
pet320.zaposinvalidi AS zaposinvalidi
ON
zaposinvalidi.zi_zaposleni = verzijaplaca.vpl_zaposleni and zi_datdo is null
INNER JOIN
pet320.verzijasumstavki AS verzijasumstavki
ON
verzijasumstavki.vss_verzije = verzijaplaca.vpl_verzije AND
verzijasumstavki.vss_zaposleni = verzijaplaca.vpl_zaposleni AND
verzijasumstavki.vss_vrsteplacila = 9301
WHERE
1=1
AND vrsteplacila.vp_skupinevrpl in (1,2,3,4,16)
AND (verzijaplaca.vpl_verzije = 215)
AND (verzijaplaca.vpl_zaposleni IS NULL OR 1=1)
AND (verzijaplaca.vpl_strm_strmesta IS NULL OR 1=1)
AND (dmzaposlenih.dmz_orgenote IS NULL OR 1=1)
AND (dmzaposlenih.dmz_izplacilnamesta IS NULL OR 1=1)
AND (verzijaplaca.vpl_placilnirazredi IS NULL OR 1=1)
AND (dmzaposlenih.dmz_vrstapog IN (1,0))
AND verzijaplaca.vpl_zaposleni in (select distinct vpl_zaposleni from pet320.verzijaplaca where vpl_skupinevrpl = 16 AND vpl_verzije = 215)
group by dmzaposlenih.dmz_enotezpiz,
zaposleni.za_koda
ORDER BY
dmzaposlenih.dmz_enotezpiz,
zaposleni.za_koda
The query as you tried to write it would run
select sum(verplaca.vpl_bruto)
from pet320.verzijaplaca as verplaca
and produce the exact same result every time the case statement was true. Even if you can do it that way, you shouldn't, because it's a huge waste of time to run that query over and over. Instead, run that statement once and store the value. Then refer to the stored value whenever you need it. Here are a couple of options:
with vpl_bruto_sum as (
select sum(verplaca.vpl_bruto) as total
from pet320.verzijaplaca as verplaca
)
select sum(case when verzijaplaca.vpl_vrsteplacila = 9150
then vpl_bruto_sum.total else 0
end
)
from pet320.verzijaplaca
inner join vpl_bruto_sum on 1=1;
Or you could make thinks simpler by using the join condition instead of the inner case statement:
with vpl_bruto_sum as (
select sum(verplaca.vpl_bruto) as total
from pet320.verzijaplaca as verplaca
)
select sum(vpl_bruto_sum.total)
from pet320.verzijaplaca
left outer join vpl_bruto_sum on verzijaplaca.vpl_vrsteplacila = 9150;
If you want to calculate a value, then use it in multiple different queries, you could use a variable:
create or replace variable my_sum integer;
set my_sum = (select sum(vpl_bruto) from pet320.verzijaplaca);
select sum(case when verzijaplaca.vpl_vrsteplacila = 9150
then my_sum else 0
end
)
from pet320.verzijaplaca;
Hopefully that will help you get started.
It looks like there are probably other problems with your query as well. For example, where 1=1 and... is not a useful construct. It might be worth seeking help about how to design a better query--I think it could be a lot simpler, though it's hard to say without knowing what you are doing.