Split comma separated data and get its respective value from another table - postgresql

I have concated data in table1
id
concats
sum
1
b,c
2
a,k,f,l,s
3
b,f,t
4
a,b,h,k,l,q,s,t
5
b,c,k,f,p,s
6
a,c,q,s
and another table with value
grade
score
a
4.82
b
2.65
c
2.56
d
2.75
g
6.90
h
5.90
k
6.41
f
12.80
l
2.56
p
12.80
q
1.35
s
2.90
t
5.97
I want to update table1.sum, something like b,c=(2.65+2.56=5.21)
Tried the below mentioned code, but there is an error.
UPDATE table1 as t1 SET sum =
(SELECT (CASE WHEN (SELECT SPLIT_PART(concats,',',1) from t1) = t2.grade then t2.score ELSE 0 END) +
(CASE WHEN (SELECT SPLIT_PART(concats,',',2) from t1) = t2.grade then t2.score ELSE 0 END) +
(CASE WHEN (SELECT SPLIT_PART(concats,',',3) from t1) = t2.grade then t2.score ELSE 0 END) +
(CASE WHEN (SELECT SPLIT_PART(concats,',',4) from t1) = t2.grade then t2.score ELSE 0 END) +
(CASE WHEN (SELECT SPLIT_PART(concats,',',5) from t1) = t2.grade then t2.score ELSE 0 END) +
(CASE WHEN (SELECT SPLIT_PART(concats,',',6) from t1) = t2.grade then t2.score ELSE 0 END) +
(CASE WHEN (SELECT SPLIT_PART(concats,',',7) from t1) = t2.grade then t2.score ELSE 0 END ) +
(CASE WHEN (SELECT SPLIT_PART(concats,',',8) from t1) = t2.grade then t2.score ELSE 0 END )
FROM table2 AS t2 )

You can join the two tables by converting the dreaded CSV columns to an array, then do the GROUP BY and sum on the result of that. This can be used to update the target table:
update table1
set sum = x.sum_score
from (
select t1.id,
sum(t2.score) as sum_score
from table1 t1
join table2 t2 on t2.grade = any(string_to_array(t1.concats, ','))
group by t1.id
) x
where x.id = table1.id;

Related

SUM(CASE WHEN ...) returns a greater number than COUNT(DISTINCT..)

I have written a query in two models, but I can't figure out why the second query returns a greater number than the first one; while the number that the first one, COUNT(DISTINCT...) returns is correct:
WITH types(id) AS (VALUES('{1, 4, 5, 3}'::INTEGER[])),
date_gen64 AS
(
SELECT CAST (generate_series(date '10/1/2017', date '11/15/2017', interval
'1 day') AS date) as days ORDER BY days)
SELECT cl.class_date AS c_date,
count(DISTINCT (CASE WHEN co.id = 1 THEN p.id END)),
count(DISTINCT (CASE WHEN co.id = 2 THEN p.id END))
FROM person p
JOIN envelope e ON e.personID = p.id
JOIN "class" cl on cl.id = p.classID
JOIN course co ON co.id = cl.course_id AND co.id = 1
JOIN types ON cr.type_id = ANY (types.id)
RIGHT JOIN date_gen64 dg ON dg.days = cl.class_date
GROUP BY cl.class_date
ORDER BY cl.class_date
The above query returns 26 but following query returns 27!
The reason why I rewrote it with SUM is that the first query
was too slow. But my question is that why the second one counts more?
WITH types(id) AS (VALUES('{1, 4, 5, 3}'::INTEGER[]))
SELECT tmpcl.days,
SUM(CASE WHEN tmp80.course_id = 1 THEN 1
ELSE 0 END),
SUM(CASE WHEN tmp80.course_id = 2 THEN 1
ELSE 0 END)
FROM (
SELECT CAST (generate_series(date '10/1/2017', date '11/15/2017',
interval '1 day') AS date) as days ORDER BY days) tmpcl
LEFT JOIN (
SELECT DISTINCT p.id AS "person_id",
cl.class_date AS c_date,
co.id AS "course_id"
FROM person p
JOIN envelope e ON e.personID = p.id
JOIN "class" cl on cl.id = p.classID
JOIN course co ON co.id = cl.course_id
JOIN types ON cr.type_id = ANY (types.id)
WHERE co.id IN ( 1 , 2 )
) tmp80 ON tmpcl.days = tmp80.class_date
GROUP BY tmpcl.days
ORDER BY tmpcl.days
You can theoretically have multiple people enrolled in the same class on the same day. Indeed that would seem to be the main point of having classes. So each time there are multiple people assigned to the same class on the same day you can have a higher count than you would in your first query. Does that make sense?
You don't appear to be using p.id in that inner query so simply remove it and your counts should match.
WITH types(id) AS (VALUES('{1, 4, 5, 3}'::INTEGER[]))
SELECT tmpcl.days,
SUM(CASE WHEN tmp80.course_id = 1 THEN 1
ELSE 0 END),
SUM(CASE WHEN tmp80.course_id = 2 THEN 1
ELSE 0 END)
FROM (
SELECT CAST (generate_series(date '10/1/2017', date '11/15/2017',
interval '1 day') AS date) as days ORDER BY days) tmpcl
LEFT JOIN (
SELECT DISTINCT cl.class_date AS c_date,
co.id AS "course_id"
FROM person p
JOIN envelope e ON e.personID = p.id
JOIN "class" cl on cl.id = p.classID
JOIN course co ON co.id = cl.course_id
JOIN types ON cr.type_id = ANY (types.id)
WHERE co.id IN ( 1 , 2 )
) tmp80 ON tmpcl.days = tmp80.class_date
GROUP BY tmpcl.days
ORDER BY tmpcl.days

Capture First Character of Last Group of 1s in a Binary Series Part II: Multiple IDs

I have data something like this:
ID 1 1 1 1 1 1 1 1 1 1 1 1
Month J F M A M J J A S O N D
Status 1 0 0 1 0 1 0 0 1 1 1 1
ID 2 2 2 2 2 2 2 2 2 2 2 2
Month J F M A M J J A S O N D
Status 1 0 1 0 1 0 1 0 1 0 1 1
ID 3 3 3 3 3 3 3 3 3 3 3 3
Month J F M A M J J A S O N D
Status 0 0 0 0 0 0 0 0 0 0 0 1
Using t-SQL, I am trying to capture the month corresponding to the first STATUS = 1 in the last group of 1s for each ID, i.e., September, November and December in this example.
Here is the code I'm using:
IF OBJECT_ID('tempdb..#Temp1') IS NOT NULL DROP TABLE #Temp1
;WITH PARTITIONED1 AS
(SELECT t0.ID
, t0.Year_Month
, LAST_VALUE(t0.Year_Month) OVER (PARTITION BY t0.Account_Number ORDER BY t0.Year_Month) AS STATUS
, ROW_NUMBER() OVER (PARTITION BY t0.Account_Number ORDER BY t0.Year_Month) AS rn1
FROM #Temp0 t0
)
SELECT *
INTO #Temp1
FROM PARTITIONED1 p1
ORDER BY t0.ID
, t0.Year_Month
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL DROP TABLE #Temp
SELECT *
INTO #Temp
FROM #Temp1 t1
WHERE t1.rn1 = (SELECT MAX(b.rn1) + 1 FROM #Temp1 b WHERE b.STATUS = 0)
GROUP BY t1.ID
, t1.Year_Month
, t1.rn1
However, this just returns the last instance where STATUS = 1 is achieved overall as the first 1 of the last group of 1s, in this case January.
I've tried using CASE statements and grouping in various combinations (hence the intermediate step reading the data into #Temp1), but have not been able to get results for all three IDs; is anyone able to assist?
Thanks in advance!
Assuming Ju for June and Jl for July:
--Sample Data
IF OBJECT_ID('tempdb..#Temp0') IS NOT NULL DROP TABLE #Temp0
CREATE TABLE #Temp0 (ID INT, Year_Month VARCHAR(1), Status INT)
INSERT INTO #Temp0
VALUES(1,'J',1),(1,'F',0),(1,'M',0),(1,'A',1),(1,'M',0),(1,'J',1),(1,'J',0),(1,'A',0),(1,'S',1),(1,'O',1),(1,'N',1),(1,'D',1),(2,'J',1),(2,'F',0),(2,'M',1),(2,'A',0),(2,'M',1),(2,'J',0),(2,'J',1),(2,'A',0),(2,'S',1),(2,'O',0),(2,'N',1),(2,'D',1),(3,'J',0),(3,'F',0),(3,'M',0),(3,'A',0),(3,'M',0),(3,'J',0),(3,'J',0),(3,'A',0),(3,'S',0),(3,'O',0),(3,'N',0),(3,'D',1);
--Query
WITH A
AS ( SELECT *,
CASE Year_Month
WHEN 'J' THEN 1
WHEN 'F' THEN 2
WHEN 'M' THEN 3
WHEN 'A' THEN 4
WHEN 'M' THEN 5
WHEN 'Ju' THEN 6
WHEN 'Jl' THEN 7
WHEN 'A' THEN 8
WHEN 'S' THEN 9
WHEN 'O' THEN 10
WHEN 'N' THEN 11
WHEN 'D' THEN 12
END
AS MonthNumber
FROM #Temp0 ),
StartingPoints
AS ( SELECT ID,
Year_Month,
MonthNumber,
Status
FROM A
WHERE NOT EXISTS
(
SELECT 1
FROM A
AS B
WHERE B.ID=A.ID
AND B.Status=A.Status-1
) ),
MonthRanking
AS ( SELECT A.*,
ROW_NUMBER( ) OVER( PARTITION BY A.ID ORDER BY A.MonthNumber )
AS rownum
FROM A
INNER JOIN
(
SELECT ID,
MAX( MonthNumber )+1
AS StartOfLastGroup
FROM StartingPoints
GROUP BY ID
)
AS B
ON A.ID=B.ID
AND A.MonthNumber>=B.StartOfLastGroup )
SELECT *
FROM MonthRanking
WHERE rownum=1;
Results:
If Month Names are recorded in Full as in July, June then this would work as well:
WITH StartingPoints
AS (SELECT ID,
Year_Month,
MonthNUmber = MONTH('01-'+Year_Month+'-2010'),
Status
FROM #Temp0
WHERE NOT EXISTS
(
SELECT 1
FROM #Temp0 AS B
WHERE B.ID = #Temp0.ID
AND B.Status = #Temp0.Status - 1
)),
MonthRanking
AS (SELECT A.*,
ROW_NUMBER() OVER(PARTITION BY A.ID ORDER BY MONTH('01-'+A.Year_Month+'-2010')) AS rownum
FROM #Temp0 AS A
INNER JOIN
(
SELECT ID,
MAX(MonthNumber) + 1 AS StartOfLastGroup
FROM StartingPoints
GROUP BY ID
) AS B ON A.ID = B.ID
AND MONTH('01-'+A.Year_Month+'-2010') >= B.StartOfLastGroup)
SELECT *
FROM MonthRanking
WHERE rownum = 1;
Results:
And if we assume that the data is as Iamdave assumes then it simply like so:
WITH StartingPoints
AS (SELECT ID,
Year_Month,
Status
FROM #Temp0
WHERE NOT EXISTS
(
SELECT 1
FROM #Temp0 AS B
WHERE B.ID = #Temp0.ID
AND B.Status = #Temp0.Status - 1
)),
MonthRanking
AS (SELECT A.*,
ROW_NUMBER() OVER(PARTITION BY A.ID ORDER BY Year_Month) AS rownum
FROM #Temp0 AS A
INNER JOIN
(
SELECT ID,
MAX(Year_Month) + 1 AS StartOfLastGroup
FROM StartingPoints
GROUP BY ID
) AS B ON A.ID = B.ID
AND A.Year_Month >= B.StartOfLastGroup)
SELECT *
FROM MonthRanking
WHERE rownum = 1;
Results:
You can do this with a couple derived tables that stack two window functions on top of one another (which can't be done in the same select). I have assumed that your data is slightly different to the table you have provided, based on the column names in your query. If they are not as I have them below, I strongly recommend having a look at how you store your data:
declare #t table(ID int, YearMonth int,StatusValue bit);
insert into #t values (1,201501,1),(1,201502,0),(1,201503,0),(1,201504,1),(1,201505,0),(1,201506,1),(1,201507,0),(1,201508,0),(1,201509,1),(1,201510,1),(1,201511,1),(1,201512,1),(2,201601,1),(2,201602,0),(2,201603,1),(2,201604,0),(2,201605,1),(2,201606,0),(2,201607,1),(2,201608,0),(2,201609,1),(2,201610,0),(2,201611,1),(2,201612,1),(3,201701,0),(3,201702,0),(3,201703,0),(3,201704,0),(3,201705,0),(3,201706,0),(3,201707,0),(3,201708,0),(3,201709,0),(3,201710,0),(3,201711,0),(3,201712,1);
with c as
(
select ID
,YearMonth
,StatusValue
,case when StatusValue = 1
and lead(StatusValue,1,1) over (partition by ID
order by YearMonth desc) = 0
then 1
else 0
end as c
from #t
), sc as
(
select ID
,YearMonth
,StatusValue
,sum(c) over (partition by ID order by YearMonth desc) as sc
from c
where c = 1
)
select ID
,YearMonth
,StatusValue
from sc
where sc = 1
order by ID;
Output:
+----+-----------+-------------+
| ID | YearMonth | StatusValue |
+----+-----------+-------------+
| 1 | 201509 | 1 |
| 2 | 201611 | 1 |
| 3 | 201712 | 1 |
+----+-----------+-------------+

How to append CTE results to main query output?

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

db2 case when subselect

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.

set value from select for few select

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