Sum two columns values in same table on postgresql query - postgresql

SELECT c.period,
c.idsr_incident_id_id,
c.idsr_disease_id_id,
CASE WHEN idsr_incident_id_id = 1 OR idsr_incident_id_id = 3 THEN SUM(c.data_value::integer) ELSE 0 END AS cases,
CASE WHEN idsr_incident_id_id = 2 OR idsr_incident_id_id = 4 THEN SUM(c.data_value::integer) ELSE 0 END AS deaths
FROM veoc_idsr_weekly_national_report c
LEFT JOIN veoc_idsr_diseases b ON b.id = c.idsr_disease_id_id
LEFT JOIN veoc_idsr_reported_incidents j ON j.id = c.idsr_incident_id_id
WHERE c.idsr_incident_id_id >= 1 AND c.idsr_incident_id_id <= 4 AND idsr_disease_id_id = 10 AND period ='2019W30'
GROUP BY c.period, c.idsr_incident_id_id, c.idsr_disease_id_id, c.data_value;`enter code here`
Below my query results:
I want to sum the cases and the death value columns since the period and disease_id is the same. I think my problem is on the Group By section but I cant solve it. If it means i must remove the incident_id column to get the totals it will still be fine.

Please, try with below query where sum of function place replaced:
SELECT c.period,
c.idsr_disease_id_id,
SUM(CASE WHEN idsr_incident_id_id = 1 OR idsr_incident_id_id = 3 THEN (c.data_value::integer) ELSE 0 END) AS cases,
SUM(CASE WHEN idsr_incident_id_id = 2 OR idsr_incident_id_id = 4 THEN (c.data_value::integer) ELSE 0 END) AS deaths
FROM veoc_idsr_weekly_national_report c
LEFT JOIN veoc_idsr_diseases b ON b.id = c.idsr_disease_id_id
LEFT JOIN veoc_idsr_reported_incidents j ON j.id = c.idsr_incident_id_id
WHERE c.idsr_incident_id_id >= 1 AND c.idsr_incident_id_id <= 4 AND idsr_disease_id_id = 10 AND period ='2019W30'
GROUP BY c.period, c.idsr_disease_id_id;

Related

How do I unpivot a result of a query with sum Case when involving inner joins of many tables?

I have a mission to query various tables and sum up their values based on options selected by the user and the way that i found to do that came from here by using sum case when then and else.
Now my dilema is that i am able to get the results but the are structured only in columns but i would love them to be structured in rows, so i discovered pivot and unpivot but unfortunately i can't get my results in rows.
Here is my query:
select
SUM(CASE WHEN opcao = 'ABC' THEN 1 ELSE 0 END) as ABC,
SUM(CASE WHEN opcao = 'DEF' THEN 1 ELSE 0 END) as DEF,
SUM(CASE WHEN opcao = 'GHI' THEN 1 ELSE 0 END) as GHI,
SUM(CASE WHEN opcao = 'JKL' THEN 1 ELSE 0 END) as JKL,
SUM(CASE WHEN opcao = 'MNO' THEN 1 ELSE 0 END) as MNO,
from
paciente_paciente pp
inner join coleta_preenchimento cp on cp.paciente_id = pp.paciente_id
inner join coleta_preenchimento_pergunta cpp on cpp.preenchimento_id = cp.preenchimento_id
inner join coleta_pergunta_opcao cpo on cpo.opcao_id = cpp.opcao_id
inner join coleta_atendimento_formulario caf on caf.preenchimento_id = cp.preenchimento_id
inner join coleta_atendimento ca on ca.atendimento_id = caf.atendimento_id
where
ca.status = 'FINALIZADO'
and cpp.pergunta_id= 1076
Result that I am getting:
ABC
DEF
GHI
JKL
MNO
0
1
1
0
1
Result expected:
OPTION
VALUE
ABC
0
DEF
1
GHI
1
JKL
0
MNO
1
Thanks in advance for all the help!
Generally speaking, you want to be aggregating by the opcao column here. And you should start the query with the table coleta_pergunta_opcao and then left join out.
SELECT opcao AS OPTION, COUNT(ca.atendimento_id) AS VALUE
FROM coleta_pergunta_opcao cpo
LEFT JOIN coleta_preenchimento_pergunta cpp
ON cpo.opcao_id = cpp.opcao_id AND
cpp.pergunta_id = 1076
LEFT JOIN coleta_preenchimento cp
ON cpp.preenchimento_id = cp.preenchimento_id
LEFT JOIN paciente_paciente pp
ON cp.paciente_id = pp.paciente_id
LEFT JOIN coleta_atendimento_formulario caf
ON caf.preenchimento_id = cp.preenchimento_id
LEFT JOIN coleta_atendimento ca
ON ca.atendimento_id = caf.atendimento_id AND
ca.status = 'FINALIZADO'
GROUP BY
opcao;

T-SQL Two counts with different where clause

I want to count values on a table with different where clauses and wondering if there is a better way of doing it.
In this code i count one value.
SELECT v.name, count(v.value) AS v1
FROM dbo.table as v
WHERE v.organisationID = 2
AND v.datecreated > '2018-01-01'
AND v.datecreated < '2018-05-01'
AND v.value = 1
GROUP BY v.name
I also want to count all rows with value = 2
my way of doing it is like this with a sub select.
SELECT v.name, count(v.value) AS v1, (SELECT v2.name, count(v2.value)
FROM dbo.table as v2
WHERE v2.organisationID = 2
AND v2.datecreated > '2018-01-01'
AND v2.datecreated < '2018-05-01'
AND v2.value = 2
GROUP BY v2.name) AS v2
FROM dbo.table as v
WHERE v.organisationID = 2
AND v.datecreated > '2018-01-01'
AND v.datecreated < '2018-05-01'
AND v.value = 1
GROUP BY v.name
The table contains > 100 millions rows so I really want the fastest way. I use clustered columnstore index on the table.
Is there some way of doing it whitout sub-select.
Pseudo code:
SELECT v.name, count(v.value where v.value=1) AS v1, count(v.value where v.value=2) AS v2
FROM dbo.table as v
WHERE v.organisationID = 2
AND v.datecreated > '2018-01-01'
AND v.datecreated < '2018-05-01'
GROUP BY v.name
Yes, just use a CASE expression:
SELECT v.name,
SUM(CASE WHEN v.value = 1 THEN 1 ELSE 0 END) AS v1,
SUM(CASE WHEN v.value = 2 THEN 1 ELSE 0 END) AS v2
FROM dbo.table as v
WHERE v.organisationID = 2
AND v.datecreated > '2018-01-01'
AND v.datecreated < '2018-05-01'
AND v.value IN (1,2)
GROUP BY v.name
;

Sum of a column with the same name (value) in PostgreSQL

I am using the following query in PostgreSQL:
SELECT
pegawai_nama,
COUNT(operasi_operator_dokter) AS total,
CASE tindakan_golongan WHEN 'KECIL' THEN SUM(tariftindakan_biaya_alkes)
ELSE 0
END AS KECIL,
CASE tindakan_golongan WHEN 'BESAR' THEN SUM(tariftindakan_biaya_alkes)
ELSE 0
END AS BESAR,
CASE tindakan_golongan WHEN 'KHUSUS' THEN SUM(tariftindakan_biaya_alkes
ELSE 0
END AS SEDANG
FROM
t_operasi
LEFT JOIN m_pasien On t_operasi.operasi_pasien_norm = m_pasien.pasien_norm
LEFT JOIN t_pendaftaran on t_operasi.operasi_pendaftaran_id = t_pendaftaran.pendaftaran_id
LEFT JOIN m_tindakan ON t_operasi.operasi_tindakan_id = m_tindakan.tindakan_id
LEFT JOIN m_tarif_tindakan ON m_tindakan.tindakan_id = m_tarif_tindakan.m_tindakan_id
LEFT JOIN m_pegawai ON cast(m_pegawai.pegawai_id as varchar(10)) = t_operasi.operasi_operator_dokter
LEFT JOIN t_diagnosa_pasien ON t_diagnosa_pasien.t_pendaftaran_id = t_pendaftaran.pendaftaran_id
LEFT JOIN m_icd ON m_icd.icd_id = t_diagnosa_pasien.m_icd_id
WHERE operasi_id IS NOT NULL AND tindakan_golongan IN ('KECIL', 'BESAR', 'KHUSUS', 'SEDANG', '')
GROUP BY pegawai_nama, tindakan_golongan;
However, the result below is not what I am after:
Instead I would like the following result:
pegawai_nama total kecil besar sedang khusus
DR. JOKO TRIYONO, SPM 2 189000 0 909700 0
DR. DJOHAR ANWAR 3 567000 0 0 0
Just have this as a nested query, and group it again:
select pegawai_nama, sum(total) as total , sum(kecil) as kecil, sum(besar) as besar, sum(sedang) as sedang
from (
-- insert your query here
) sub
group by pegawai_nama
Try taking out the "tindakan_golongan" column from the GROUP BY.
This is my new code (based on Georgi Raychev's answer):
SELECT
sub.pegawai_nama,
sum(sub.total) as total,
sum(sub.kecil) as kecil,
sum(sub.besar) as besar,
sum(sub.sedang) as sedang,
sum(sub.khusus) as khusus
FROM (
SELECT
pegawai_nama,
COUNT(operasi_operator_dokter) AS total,
CASE tindakan_golongan WHEN 'KECIL' THEN SUM(tariftindakan_biaya_alkes +
tariftindakan_biaya_cover +tariftindakan_biaya)
ELSE 0
END AS kecil,
CASE tindakan_golongan WHEN 'BESAR' THEN SUM(tariftindakan_biaya_alkes +
tariftindakan_biaya_cover +tariftindakan_biaya)
ELSE 0
END AS besar,
CASE tindakan_golongan WHEN 'KHUSUS' THEN SUM(tariftindakan_biaya_alkes +
tariftindakan_biaya_cover +tariftindakan_biaya)
ELSE 0
END AS khusus,
CASE tindakan_golongan WHEN 'SEDANG' THEN SUM(tariftindakan_biaya_alkes +
tariftindakan_biaya_cover +tariftindakan_biaya)
ELSE 0
END AS sedang
FROM
t_operasi
LEFT JOIN m_pasien On t_operasi.operasi_pasien_norm = m_pasien.pasien_norm
LEFT JOIN t_pendaftaran on t_operasi.operasi_pendaftaran_id = t_pendaftaran.pendaftaran_id
LEFT JOIN m_tindakan ON t_operasi.operasi_tindakan_id = m_tindakan.tindakan_id
LEFT JOIN m_tarif_tindakan ON m_tindakan.tindakan_id = m_tarif_tindakan.m_tindakan_id
LEFT JOIN m_pegawai ON cast(m_pegawai.pegawai_id as varchar(10)) = t_operasi.operasi_operator_dokter
LEFT JOIN t_diagnosa_pasien ON t_diagnosa_pasien.t_pendaftaran_id = t_pendaftaran.pendaftaran_id
LEFT JOIN m_icd ON m_icd.icd_id = t_diagnosa_pasien.m_icd_id
WHERE operasi_id IS NOT NULL
GROUP BY pegawai_nama, tindakan_golongan
) AS sub
GROUP BY sub.pegawai_nama
;
And this is the result:
New Result

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.

Problem counting item frequency on T-SQL

I'm trying to count the frequency of numbers from 1 to 100 on different fields of a table.
Let's say I have the table "Results" with the following data:
LottoId Winner Second Third
--------- --------- --------- ---------
1 1 2 3
2 1 2 3
I'd like to be able to get the frequency per numbers. For that I'm using the following code:
--Creating numbers temp table
CREATE TABLE #Numbers(
Number int)
--Inserting the numbers into the temp table
declare #counter int
set #counter = 0
while #counter < 100
begin
set #counter = #counter + 1
INSERT INTO #Numbers(Number) VALUES(#counter)
end
--
SELECT #Numbers.Number, Count(Results.Winner) as Winner,Count(Results.Second) as Second, Count(Results.Third) as Third FROM #Numbers
LEFT JOIN Results ON
#Numbers.Number = Results.Winner OR #Numbers.Number = Results.Second OR #Numbers.Number = Results.Third
GROUP BY #Numbers.Number
The problem is that the counts are repeating the same values for each number. In this particular case I'm getting the following result:
Number Winner Second Third
--------- --------- --------- ---------
1 2 2 2
2 2 2 2
3 2 2 2
...
When I should get this:
Number Winner Second Third
--------- --------- --------- ---------
1 2 0 0
2 0 2 0
3 0 0 2
...
What am I missing?
If you are using SQL Server 2005+
With
WinnerCounts As
(
Select #Numbers.Number, Count(Results.Winner) As Results
FROM #Numbers
JOIN Results
On #Numbers.Number = Results.Winner
)
, SecondCounts As
(
Select #Numbers.Number, Count(Results.Second) As Results
FROM #Numbers
JOIN Results
On #Numbers.Number = Results.Second
)
, ThirdCounts As
(
Select #Numbers.Number, Count(Results.Third) As Results
FROM #Numbers
JOIN Results
On #Numbers.Number = Results.Third
)
Select Numbers.Number, Coalesce(WinnerCounts.Results,0) As Winner, Coalesce(SecondCounts.Result,0) As Second, Coalesce(ThirdCounts.Result,0) As Third
From #Numbers
Left Join WinnerCounts
On WinnerCounts.Results = #Numbers.Number
Left Join SecondCounts
On SecondCounts.Results = #Numbers.Number
Left Join ThirdCounts
On ThirdCounts.Results = #Numbers.Number
Another possible solution which will work in older versions of SQL Server:
Select #Numbers.Number
, SUM( Case When Winners.Winner Is Not Null Then 1 Else 0 End ) As WinnerCount
, SUM( Case When Seconds.Second Is Not Null Then 1 Else 0 End ) As SecondCount
, SUM( Case When Thirds.Third Is Not Null Then 1 Else 0 End ) As ThirdCount
From #Numbers
Left Join Results As Winners
On Winners.Winner = #Numbers.Number
Left Join Results As Seconds
On Seconds.Second = #Numbers.Number
Left Join Results As Thirds
On Thirds.Third = #Numbers.Number
Group By #Numbers.Number
You can use PIVOT and UNPIVOT.
SELECT Number, Winner, Second, Third
FROM (SELECT LottoID, Ranking, Number
FROM Lotto UNPIVOT (Number FOR Ranking
IN ([Winner], [Second], [Third])) AS unpvt) flat
PIVOT (COUNT(LottoId) FOR Ranking
IN ([Winner], [Second], [Third])) crosstab