SELECT with CASE WHEN and value after THEN instead of String - postgresql

My query is:
SELECT
id,
CASE WHEN EXISTS(
SELECT
data_od
FROM
bp_stan_produkt
WHERE
id_produkt = bp_produkt.id AND data_do IS NULL AND id_stan_produkt = 313
) THEN 'TAK' ELSE 'NIE'
END AS "313"
FROM
bp_produkt
WHERE
id IN(21048528)
Is it possible to put data_od to column 313 instead of TAK or do I have to create function, make SELECT data_od into some_variable and then some_variable?

Yes it is possible:
select id,
case when exists (select data_od from bp_stan_produkt
where id_produkt = bp_produkt.id and data_do is null
and id_stan_produkt = 313)
then (select to_char(data_od, 'YYYY-MM-DD')
from bp_stan_produkt
where id_produkt = bp.id
and data_do is null
and id_stan_produkt = 313)
else 'NIE'
end as "313"
from bp_produkt
where id in(21048528);
EDIT:
SELECT bp.id, COALESCE(t.data_od_t, 'NIE') AS "313"
FROM bp_produkt bp
LEFT JOIN LATERAL (select to_char(data_od, 'YYYY-MM-DD') AS data_od_t
from bp_stan_produkt
where id_produkt = bp.id
and data_do is null
and id_stan_produkt = 313) t
ON TRUE
WHERE bp.id in(21048528)

Related

SELECT Value even if NULL on LEFT JOIN

I am trying to pull data out and chuck it into a Stimulsoft report. The problem I am having is that I need it to output to two columns. I also need every "manager" record to show even if the count assigned to said record is NULL.
This is what i have at the moment:
DECLARE #ManagerCount INT = (( SELECT Count(*) FROM AM WHERE dbo.AM.AMCurrent = 1 AND dbo.AM.OmitInReport = 0 ) + 1) / 2
DECLARE #tmp_AM1 TABLE (AMID INT, AMName NVARCHAR(100), ID INT)
INSERT INTO #tmp_AM1 SELECT AMID, AMName, row_number() over (order by AMID ) FROM AM
WHERE dbo.AM.AMCurrent = 1 AND dbo.AM.OmitInReport = 0
SELECT * FROM (
SELECT ta.id AS id1, ta.AMName AS ManagerName1, COUNT(*) AS ManagerCount1 FROM #tmp_AM1 tA INNER JOIN Job J ON tA.AMID = j.AMID
WHERE ta.ID BETWEEN 1 AND #ManagerCount AND j.jobStatusID != 5
GROUP BY ta.ID, ta.AMName
) a
LEFT JOIN
(
SELECT ta.id AS id2,ta.AMName AS ManagerName2, COUNT(*) AS ManagerCount2 FROM #tmp_AM1 tA INNER JOIN Job J ON tA.AMID = j.AMID
WHERE ta.ID > #ManagerCount AND j.jobStatusID != 5
GROUP BY ta.AMName, ta.ID
) b ON a.id1 + #ManagerCount = b.id2
Which ends up returning something like:
There are 18 managers so 9 per column, but this code doesn't show them all since anything that doesn't have a count in the first left join, won't show, and therefore the same row in column 2 doesn't show.
Results of SELECT * FROM #tmp_AM1:
DECLARE #tmp_AM1 TABLE (AMID INT, AMName NVARCHAR(100), ID INT)
INSERT INTO #tmp_AM1 SELECT AMID, AMName, row_number() over (order by AMID ) FROM AM
WHERE dbo.AM.AMCurrent = 1 AND dbo.AM.OmitInReport = 0
SELECT * FROM (
SELECT ta.id AS id1, ta.AMName AS ManagerName1, COUNT(*) AS ManagerCount1 FROM #tmp_AM1 tA INNER JOIN Job J ON tA.AMID = j.AMID
WHERE ta.ID BETWEEN 1 AND #ManagerCount AND j.jobStatusID != 5
GROUP BY ta.ID, ta.AMName
) a
LEFT OUTER JOIN
(
SELECT ta.id AS id2,ta.AMName AS ManagerName2, COUNT(*) AS ManagerCount2 FROM #tmp_AM1 tA INNER JOIN Job J ON tA.AMID = j.AMID
WHERE ta.ID > #ManagerCount AND j.jobStatusID != 5
GROUP BY ta.AMName, ta.ID
) b ON a.id1 + #ManagerCount = b.id2 where ManagerName2 IS Null and ManagerCount2 IS NULL
just you want to use LEFT OUTER JOIN for select row even there is have any null values.,
Since the two subqueries are pretty much identical, except the where-statement, I would consiter rewriting it into one single query. I'm not sure why you need the same columns outputed into different columns in the result, but something like this might work:
WITH cte AS (
SELECT
ta.id AS id
,ta.AMName AS ManagerName
,COUNT(*) AS ManagerCount
,CASE WHEN ta.ID BETWEEN 1 AND #ManagerCount THEN 0 ELSE 1 END AS something
FROM
#tmp_AM1 tA
INNER JOIN Job J ON tA.AMID = j.AMID
WHERE
j.jobStatusID != 5
GROUP BY
ta.ID
,ta.AMName
,CASE WHEN ta.ID BETWEEN 1 AND #ManagerCount THEN 0 ELSE 1 END
)
SELECT
CASE WHEN something = 0 THEN cte.id ELSE null END AS id1
,CASE WHEN something = 0 THEN cte.ManagerName ELSE null END AS ManagerName1
,CASE WHEN something = 0 THEN cte.ManagerCount ELSE null END AS ManagerCount1
,CASE WHEN something = 1 THEN cte.id ELSE null END AS id2
,CASE WHEN something = 1 THEN cte.ManagerName ELSE null END AS ManagerName2
,CASE WHEN something = 1 THEN cte.ManagerCount ELSE null END AS ManagerCount2
FROM
cte
Probably not the best approach but i got the correct output using:
DECLARE #ManagerCount INT = (( SELECT Count(*) FROM AM WHERE dbo.AM.AMCurrent = 1 AND dbo.AM.OmitInReport = 0 ) + 1) / 2
DECLARE #tmp_AM1 TABLE (AMID INT, AMName NVARCHAR(100), ID INT)
INSERT INTO #tmp_AM1 SELECT AMID, AMName, row_number() over (order by AMID ) FROM AM
WHERE dbo.AM.AMCurrent = 1 AND dbo.AM.OmitInReport = 0
ORDER By AMName
SELECT ManagerName1, ManagerName2, ManagerCount1, ManagerCount2 FROM (
SELECT AMID, ta.id AS id1, ta.AMName AS ManagerName1 FROM #tmp_AM1 tA
WHERE (ta.ID BETWEEN 1 AND #ManagerCount)
) a
LEFT JOIN
(
SELECT AMID, ISNULL(COUNT(*), 0) AS ManagerCount1 FROM Job j
INNER JOIN tblJobOutcome jO ON j.JobOutcomeID = jo.JobOutcomeID AND jO.JobOutcomeID != 5
GROUP BY AMID
) a1 ON a.AMID = a1.AMID
LEFT JOIN
(
SELECT AMID, ta.id AS id2, ta.AMName AS ManagerName2 FROM #tmp_AM1 tA
WHERE (ta.ID > #ManagerCount)
) b ON a.id1 + #ManagerCount = b.id2
LEFT JOIN
(
SELECT AMID, ISNULL(COUNT(*), 0) AS ManagerCount2 FROM Job j
INNER JOIN tblJobOutcome jO ON j.JobOutcomeID = jo.JobOutcomeID AND jO.JobOutcomeID != 5
GROUP BY AMID
) b1 ON b.AMID = b1.AMID
Gives me the correct output in two columns.
gives me this:

How to write valid If clause inside select or write function

I have procedure like this and I get error in If clause. I think it is because COUNT. But my clause have to be like that so I don't know how to solve it. Maybe it would be good to create a function or something similar. Rest of the code is okay
CREATE PROCEDURE DohvatiSveUgovore #zavodId int
AS
BEGIN
DECLARE #TempUgovori TABLE
(
Id int,
UstrojstvenaJedinica nvarchar(100),
VrstaUgovora nvarchar(100),
KlasaUgovora nvarchar(100),
UrudzbeniBrojUgovora nvarchar(100),
DatumPocetkaUgovora nvarchar(10),
DatumIstekaUgovora nvarchar(10)
)
INSERT INTO #TempUgovori(Id, UstrojstvenaJedinica, VrstaUgovora, KlasaUgovora, UrudzbeniBrojUgovora, DatumPocetkaUgovora, DatumIstekaUgovora)
SELECT
u.Id,
ISNULL(STRING_AGG(LTRIM(RTRIM(z.SkraceniNaziv)), ', '), '') AS 'UstrojstvenaJedinica',
vu.Naziv AS 'VrstaUgovora',
ISNULL(u.KlasaUgovora, '') AS 'KlasaUgovora',
ISNULL(u.UrudzbeniBrojUgovora, '') AS 'UrudzbeniBrojUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumPocetkaUgovora, 104), '')) AS 'DatumPocetkaUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumIstekaUgovora, 104), '')) AS 'DatumIstekaUgovora'
FROM Ugovor AS u
LEFT JOIN VezaUgovorUstrojstvenaJedinica AS vuu
ON u.Id = vuu.UgovorId
INNER JOIN SifVrstaUgovora AS vu
ON u.VrstaUgovoraId = vu.Id
LEFT JOIN [TEST_MaticniPodaci2].hcphs.SifZavod AS z
ON vuu.UstrojstvenaJedinicaId = z.Id
if( (SELECT COUNT(UstrojstvenaJedinicaId) FROM VezaUgovorUstrojstvenaJedinica WHERE UstrojstvenaJedinicaId = 'HCPHS') = 1)
begin
(SELECT * FROM VezaUgovorUstrojstvenaJedinica WHERE UstrojstvenaJedinicaId = 'HCPHS')
end
ELSE
(SELECT * FROM VezaUgovorUstrojstvenaJedinica WHERE Isdeleted = 0 and UstrojstvenaJedinicaId = #zavodId)
end
ERROR is here in Group by and I don't know why.
GROUP BY u.Id, vu.Naziv, u.KlasaUgovora, u.UrudzbeniBrojUgovora, u.DatumPocetkaUgovora, u.DatumIstekaUgovora
SELECT
tu.Id,
tu.UstrojstvenaJedinica AS 'UstrojstvenaJedinica',
tu.VrstaUgovora AS 'VrstaUgovora',
tu.KlasaUgovora AS 'KlasaUgovora',
tu.UrudzbeniBrojUgovora AS 'UrudzbeniBrojUgovora',
tu.DatumIstekaUgovora AS 'DatumPocetkaUgovora',
tu.DatumIstekaUgovora AS 'DatumIstekaUgovora',
ISNULL(STRING_AGG(LTRIM(RTRIM(p.Naziv)), ', '), '') as 'Partner'
FROM #TempUgovori AS tu
LEFT JOIN VezaUgovorPartner AS vup
on tu.Id = vup.UgovorId
LEFT JOIN [TEST_MaticniPodaci2].dbo.Partner as p
ON vup.PartnerId = p.PartnerID
GROUP BY tu.Id, tu.UstrojstvenaJedinica, tu.VrstaUgovora, tu.KlasaUgovora, tu.UrudzbeniBrojUgovora, tu.DatumPocetkaUgovora, tu.DatumIstekaUgovora
END
EXEC [TEST_Ugovori_Prod].[dbo].[DohvatiSve] 6;
GO
I am sorry for too much code but without it I can't run query.
It looks like you're trying to tell SQL Server to join to VezaUgovorUstrojstvenaJedinica differently depending on the circumstances. The sql engine can't figure that out. For a very brief discussion on how sql evaluates a query, here's a start:
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/70efeffe-76b9-4b7e-b4a1-ba53f5d21916/order-of-execution-of-sql-queries?forum=transactsql
Maybe something like this will work for you?
CREATE PROCEDURE DohvatiSveUgovore #zavodId int
AS
BEGIN
DECLARE #TempUgovori TABLE
(
Id int,
UstrojstvenaJedinica nvarchar(100),
VrstaUgovora nvarchar(100),
KlasaUgovora nvarchar(100),
UrudzbeniBrojUgovora nvarchar(100),
DatumPocetkaUgovora nvarchar(10),
DatumIstekaUgovora nvarchar(10)
);
DECLARE #HCPHS integer;
SELECT
#HCPHS = COUNT(UstrojstvenaJedinicaId)
FROM
VezaUgovorUstrojstvenaJedinica
WHERE
UstrojstvenaJedinicaId = 'HCPHS';
IF #HCPHS = 1
INSERT INTO #TempUgovori(Id, UstrojstvenaJedinica, VrstaUgovora, KlasaUgovora, UrudzbeniBrojUgovora, DatumPocetkaUgovora, DatumIstekaUgovora)
SELECT
u.Id,
ISNULL(STRING_AGG(LTRIM(RTRIM(z.SkraceniNaziv)), ', '), '') AS 'UstrojstvenaJedinica',
vu.Naziv AS 'VrstaUgovora',
ISNULL(u.KlasaUgovora, '') AS 'KlasaUgovora',
ISNULL(u.UrudzbeniBrojUgovora, '') AS 'UrudzbeniBrojUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumPocetkaUgovora, 104), '')) AS 'DatumPocetkaUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumIstekaUgovora, 104), '')) AS 'DatumIstekaUgovora'
FROM Ugovor AS u
LEFT JOIN VezaUgovorUstrojstvenaJedinica AS vuu
ON u.Id = vuu.UgovorId
INNER JOIN SifVrstaUgovora AS vu
ON u.VrstaUgovoraId = vu.Id
LEFT JOIN [TEST_MaticniPodaci2].hcphs.SifZavod AS z
ON vuu.UstrojstvenaJedinicaId = z.Id
<JOIN OF SOME KIND>
(SELECT * FROM VezaUgovorUstrojstvenaJedinica WHERE UstrojstvenaJedinicaId = 'HCPHS')
ON <SOME CRITERIA>
GROUP BY u.Id, vu.Naziv, u.KlasaUgovora, u.UrudzbeniBrojUgovora, u.DatumPocetkaUgovora, u.DatumIstekaUgovora
ELSE
INSERT INTO #TempUgovori(Id, UstrojstvenaJedinica, VrstaUgovora, KlasaUgovora, UrudzbeniBrojUgovora, DatumPocetkaUgovora, DatumIstekaUgovora)
SELECT
u.Id,
ISNULL(STRING_AGG(LTRIM(RTRIM(z.SkraceniNaziv)), ', '), '') AS 'UstrojstvenaJedinica',
vu.Naziv AS 'VrstaUgovora',
ISNULL(u.KlasaUgovora, '') AS 'KlasaUgovora',
ISNULL(u.UrudzbeniBrojUgovora, '') AS 'UrudzbeniBrojUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumPocetkaUgovora, 104), '')) AS 'DatumPocetkaUgovora',
(SELECT ISNULL(convert(varchar(10), u.DatumIstekaUgovora, 104), '')) AS 'DatumIstekaUgovora'
FROM Ugovor AS u
LEFT JOIN VezaUgovorUstrojstvenaJedinica AS vuu
ON u.Id = vuu.UgovorId
INNER JOIN SifVrstaUgovora AS vu
ON u.VrstaUgovoraId = vu.Id
LEFT JOIN [TEST_MaticniPodaci2].hcphs.SifZavod AS z
ON vuu.UstrojstvenaJedinicaId = z.Id
<JOIN OF SOME KIND>
(SELECT * FROM VezaUgovorUstrojstvenaJedinica WHERE Isdeleted = 0 and UstrojstvenaJedinicaId = #zavodId)
ON <SOME CRITERIA>
GROUP BY u.Id, vu.Naziv, u.KlasaUgovora, u.UrudzbeniBrojUgovora, u.DatumPocetkaUgovora, u.DatumIstekaUgovora

SQL Functions with passing variable

this is my PostgreSQL query. Here I pass hard coded merchant id (merchant_id = 11).but I need to dynamical pass one merchant id from set of merchant id list. but I don't Know how to pass id as a variable or array by using PostgreSQL function.
select s.enabled from loyalty_scheme L
JOIN subscribe_merchant S ON (L.scheme_id = S.schemerefid)
JOIN transaction T ON (S.unipoint_customer_ref_id = T.unipoint_customer_ref_id) WHERE ((SELECT demoting_time_period from loyalty_scheme where minimum_purchase_amount =(SELECT min(minimum_purchase_amount) from loyalty_scheme where merchant_id = 11)GROUP BY scheme_id)< to_char((SELECT (DATE_PART('year', CURRENT_DATE::date) - DATE_PART('year', (select max(t.date_time) As maxdat FROM loyalty_scheme L
JOIN subscribe_merchant S ON (L.scheme_id = S.schemerefid)
JOIN transaction T ON (S.unipoint_customer_ref_id = T.unipoint_customer_ref_id) where (T.unipoint_customer_ref_id = ( select unipoint_customer_ref_id FROM subscribe_merchant where schemerefid = (SELECT scheme_id from loyalty_scheme where minimum_purchase_amount =(SELECT min(minimum_purchase_amount) from loyalty_scheme where merchant_id = 11)GROUP BY scheme_id) ) )) ::date)) * 12 +
(DATE_PART('month', CURRENT_DATE::date) - DATE_PART('month', (select max(t.date_time) As maxdat FROM loyalty_scheme L
JOIN subscribe_merchant S ON (L.scheme_id = S.schemerefid)
JOIN transaction T ON (S.unipoint_customer_ref_id = T.unipoint_customer_ref_id) where (T.unipoint_customer_ref_id = ( select unipoint_customer_ref_id FROM subscribe_merchant where schemerefid = (SELECT scheme_id from loyalty_scheme where minimum_purchase_amount =(SELECT min(minimum_purchase_amount) from loyalty_scheme where merchant_id = 11)GROUP BY scheme_id) ) ))::date))),'FM999MI'))
here is other query to find list of merchant id
select array_agg(DISTINCT merchant.merchant_id)
from merchant
this are the id Array {3,6,7,11,23,32,34,40,41,43}
in first code I hard coded 11,but i need to pass all those id one by one.Is any one know how to do it. please help me to do this
finally I found the the way to do this
here is my CODE
CREATE OR REPLACE FUNCTION getdata() RETURNS CHAR AS $enables$ DECLARE enables CHAR; my_arry INTEGER[] := (
select array_agg(DISTINCT merchant.merchant_id)
from merchant
); BEGIN FOREACH my_arry SLICE 1 IN ARRAY my_arry LOOP select s.enabled INTO enables from loyalty_scheme L JOIN subscribe_merchant S ON (L.scheme_id = S.schemerefid) JOIN transaction T ON (S.unipoint_customer_ref_id = T.unipoint_customer_ref_id) WHERE ((SELECT demoting_time_period from loyalty_scheme where minimum_purchase_amount =(SELECT min(minimum_purchase_amount) from loyalty_scheme where merchant_id = ANY(my_arry) )GROUP BY scheme_id)< to_char((SELECT (DATE_PART('year', CURRENT_DATE::date) - DATE_PART('year', (select max(t.date_time) As maxdat FROM loyalty_scheme L JOIN subscribe_merchant S ON (L.scheme_id = S.schemerefid) JOIN transaction T ON (S.unipoint_customer_ref_id = T.unipoint_customer_ref_id) where (T.unipoint_customer_ref_id = ( select unipoint_customer_ref_id FROM subscribe_merchant where schemerefid = (SELECT scheme_id from loyalty_scheme where minimum_purchase_amount =(SELECT min(minimum_purchase_amount) from loyalty_scheme where merchant_id = ANY(my_arry) )GROUP BY scheme_id) ) )) ::date)) * 12 + (DATE_PART('month', CURRENT_DATE::date) - DATE_PART('month', (select max(t.date_time) As maxdat FROM loyalty_scheme L JOIN subscribe_merchant S ON (L.scheme_id = S.schemerefid) JOIN transaction T ON (S.unipoint_customer_ref_id = T.unipoint_customer_ref_id) where (T.unipoint_customer_ref_id = ( select unipoint_customer_ref_id FROM subscribe_merchant where schemerefid = (SELECT scheme_id from loyalty_scheme where minimum_purchase_amount =(SELECT min(minimum_purchase_amount) from loyalty_scheme where merchant_id = ANY(my_arry))GROUP BY scheme_id) ) ))::date))),'FM999MI')) ;
END LOOP; RETURN enables; END; $enables$ LANGUAGE plpgsql;

Problems trying to return records from SELECT statement using Postgresql

I am NEW to Postgresql. I downloaded v9.5 of Postgresql a couple of days ago and finding this DB pretty challenging in just trying to get my result set back from a pretty length SELECT statement. I'm using the pgAdmin III product and hoping that I can see my result data but to no avail.
I've inherited this code and trying to make changes and trying NOT to HARD CODE the lines where the variables are being used if I can avoid it.
I've been googling about this for 2 days but again to no avail and I've tried many different variations but still not doing something right. Any help/direction would be appreciated.
Here is the error I'm getting:
********** Error **********
ERROR: query has no destination for result data
SQL state: 42601
Hint: If you want to discard the results of a SELECT, use PERFORM instead.
Context: PL/pgSQL function getrecords() line 14 at SQL statement
Here is my code (sorry for the length of the query):
CREATE OR REPLACE FUNCTION getRecords() RETURNS TABLE (
title TEXT,
Number_of_visits BIGINT,
Daily_Visit_Total_hours TEXT,
First_Aid_Visits BIGINT,
First_Aid_Total_hours TEXT,
Major_Accident_Visits BIGINT,
Major_Accident_Total_hours TEXT,
Illness_Visits BIGINT,
Illness_Total_hours TEXT,
Medication_Administration_Visits BIGINT,
Medication_Administration_Total_hours TEXT,
Specialization_Visits BIGINT,
Specialization_Total_hours TEXT,
Diabetic_Visits BIGINT,
Diabetic_Total_Hours TEXT) AS $$
#variable_conflict use_variable
DECLARE
SYEAR_DATE NUMERIC;
START_DATE DATE;
END_DATE DATE;
SCHOOL_ID NUMERIC;
BEGIN
SYEAR_DATE := 2015;
START_DATE := '2015-08-01';
END_DATE := '2015-12-31';
SCHOOL_ID := 002;
SELECT DISTINCT
'999 - DISTRICT TOTALS',
dailyVisitTotal.count as Number_of_visits,
round (dailyVisitTotal.duration_total / 60, 2) || 'hrs' as Daily_Visit_Total_hours,
firstAid.count as First_Aid_Visits,
round (firstAid.duration_total / 60, 2) || 'hrs' as First_Aid_Total_hours,
majorAcc.count as Major_Accident_Visits,
round (majorAcc.duration_total / 60, 2) || 'hrs' as Major_Accident_Total_hours,
illness.count as Illness_Visits,
round (illness.duration_total / 60, 2) || 'hrs' as Illness_Total_hours,
medicationAdminTotal.count as Medication_Administration_Visits,
round (medicationAdminTotal.duration_total / 60, 2) || 'hrs' as Medication_Administration_Total_hours,
specTotal.count as Specialization_Visits,
round (specTotal.duration_total / 60, 2) || 'hrs' as Specialization_Total_hours,
diabeticTotal.count as Diabetic_Visits,
round (diabeticTotal.duration_total / 60, 2) || 'hrs' as Diabetic_Total_Hours
FROM student_enrollment se
LEFT JOIN (
SELECT
se.syear,
count(*),
sum(coalesce(log_field20::numeric, 0)) as duration_total
FROM custom_field_log_entries sle
INNER JOIN student_enrollment se
on (sle.source_id=se.student_id
and se.custom_9 is null
and se.syear=SYEAR_DATE
--and se.syear=2015
and se.end_date is null)
WHERE
--student_field_id = 400000941
legacy_field_id = 400000941
and log_field2::date between START_DATE and END_DATE
--and log_field2::date between '2015-08-01' and '2015-12-31'
and (log_field20 ~ '^[0-9]+$' or log_field20 is null)
GROUP BY se.syear
) dailyVisitTotal
on (se.syear = dailyVisitTotal.syear)
LEFT JOIN (
SELECT
se.syear,
count(*),
sum(coalesce(log_field20::numeric, 0)) as duration_total
FROM custom_field_log_entries sle
INNER JOIN student_enrollment se
on (sle.source_id=se.student_id
and se.custom_9 is null
and se.syear=SYEAR_DATE
--and se.syear=2015
and se.end_date is null)
WHERE
--student_field_id = 400000941
legacy_field_id=400000941
and log_field2::date between START_DATE and END_DATE
--and log_field2::date between '2015-08-01' and '2015-12-31'
and (log_field20 ~ '^[0-9]+$' or log_field20 is null)
and log_field4='Y'
GROUP BY se.syear
) firstAid
on (se.syear = firstAid.syear)
LEFT JOIN (
SELECT
se.syear,
count(*),
sum(coalesce(log_field20::numeric, 0)) as duration_total
FROM custom_field_log_entries sle
INNER JOIN student_enrollment se
on (sle.source_id=se.student_id
and se.custom_9 is null
and se.syear=SYEAR_DATE
--and se.syear=2015
and se.end_date is null)
WHERE
--student_field_id = 400000941
legacy_field_id=400000941
and log_field2::date between START_DATE and END_DATE
--and log_field2::date between '2015-08-01' and '2015-12-31'
and (log_field20 ~ '^[0-9]+$' or log_field20 is null)
and log_field9='Y'
GROUP BY se.syear
) majorAcc
on (se.syear = majorAcc.syear)
LEFT JOIN (
SELECT
se.syear,
count(*),
sum(coalesce(log_field20::numeric, 0)) as duration_total
FROM custom_field_log_entries sle
INNER JOIN student_enrollment se
on (sle.source_id=se.student_id
and se.custom_9 is null
and se.syear=SYEAR_DATE
--and se.syear=2015
and se.end_date is null)
WHERE
--student_field_id = 400000941
legacy_field_id=400000941
and log_field2::date between START_DATE and END_DATE
--and log_field2::date between '2015-08-01' and '2015-12-31'
and (log_field20 ~ '^[0-9]+$' or log_field20 is null)
and log_field5='Y'
GROUP BY se.syear
) illness
on (se.syear = illness.syear)
LEFT JOIN (
SELECT
se.syear,
count(*),
sum(coalesce(log_field2::numeric, 0)) as duration_total
FROM custom_field_log_entries sle
INNER JOIN student_enrollment se
on (sle.source_id=se.student_id
and se.custom_9 is null
and se.syear=SYEAR_DATE
--and se.syear=2015
and se.end_date is null)
WHERE
--student_field_id = 400001237
legacy_field_id=400001237
and log_field5::date between START_DATE and END_DATE
--and log_field5::date between '2015-08-01' and '2015-12-31'
and (log_field2 ~ '^[0-9]+$' or log_field2 is null)
GROUP BY se.syear
) medicationAdminTotal
on (se.syear = medicationAdminTotal.syear)
LEFT JOIN (
SELECT
se.syear,
count(*),
sum(coalesce(log_field11::numeric, 0)) as duration_total
FROM custom_field_log_entries sle
INNER JOIN student_enrollment se
on (sle.source_id=se.student_id
and se.custom_9 is null
and se.syear=SYEAR_DATE
--and se.syear=2015
and se.end_date is null)
WHERE
--student_field_id = 400009202
legacy_field_id=400009202
and log_field3::date between START_DATE and END_DATE
--and log_field3::date between '2015-08-01' and '2015-12-31'
and (log_field11 ~ '^[0-9]+$' or log_field11 is null)
GROUP BY se.syear
) specTotal
on (se.syear = specTotal.syear)
LEFT JOIN (
SELECT
se.syear,
count(*),
sum(coalesce(log_field14::numeric, 0)) as duration_total
FROM custom_field_log_entries sle
INNER JOIN student_enrollment se
on (sle.source_id=se.student_id
and se.custom_9 is null
and se.syear=SYEAR_DATE
--and se.syear=2015
and se.end_date is null)
WHERE
--student_field_id = 400009003
legacy_field_id=400009003
and log_field1::date between START_DATE and END_DATE
--and log_field1::date between '2015-08-01' and '2015-12-31'
and (log_field14 ~ '^[0-9]+$' or log_field14 is null)
GROUP BY se.syear
) diabeticTotal
on (se.syear = diabeticTotal.syear)
WHERE
se.syear = SYEAR_DATE
--se.syear = 2015
and se.end_date is null
and se.custom_9 is null
and se.syear=SYEAR_DATE
--and se.syear=2015
and se.end_date is null
and (
specTotal.duration_total is not null
or dailyVisitTotal.duration_total is not null
or diabeticTotal.duration_total is not null
or medicationAdminTotal.duration_total is not null
)
ORDER BY 1;
END $$ LANGUAGE 'plpgsql';
SELECT * FROM getRecords();
Add RETURN QUERY before your query. That should tell postgres to return the records from your query.
BEGIN
SYEAR_DATE := 2015;
START_DATE := '2015-08-01';
END_DATE := '2015-12-31';
SCHOOL_ID := 002;
RETURN QUERY SELECT DISTINCT
'999 - DISTRICT TOTALS',
dailyVisitTotal.count as Number_of_visits,
round (dailyVisitTotal.duration_total / 60, 2) || 'hrs' as Daily_Visit_Total_hours,
firstAid.count as First_Aid_Visits,
...

How to formulate T-SQL to exclude duplicates?

I am trying to develop a query to just return non-duplicate records so that I can add these to my database, but I keep getting the duplicate record error.
I tried your solution but am still getting duplicate error problem. I deleted the 35 rows which were duplicate. What else could be causing this? Here is my query. Part of the confusion I think is that measureid is a single column in j5c_MasterMeasures, but this value comes from two fields in j5c_ListBoxMeasures_Sys.
CREATE TABLE #GOOD_RECORDS3 (STUDENTID VARCHAR(50), MEASUREDATE SMALLDATETIME, MEASUREID VARCHAR(100),
score_10 VARCHAR(100))
INSERT INTO #GOOD_RECORDS3
select A.studentid, A.measuredate, B.measurename+' ' +B.LabelName, A.score_10
from [J5C_Measures_Sys] A join [J5C_ListBoxMeasures_Sys] B on A.MeasureID = B.MeasureID
except
select A.studentid, A.measuredate, B.measurename+' ' +B.LabelName, A.score_10
from [J5C_Measures_Sys] A join [J5C_ListBoxMeasures_Sys] B on A.MeasureID = B.MeasureID
GROUP BY A.studentid, A.measuredate, B.measurename, B.LabelName, A.score_10
having COUNT(A.score_10) > 1
delete #GOOD_RECORDS3
from #GOOD_RECORDS3 a
join sysobjects so on so.name = 'J5C_Measures_Sys' AND so.type = 'u'
join syscolumns sc on so.id = sc.id and sc.name = 'score_10'
join [J5C_MeasureNamesV2_Sys] v on v.Score_field_id = sc.name
WHERE A.SCORE_10 IS NOT NULL AND A.STUDENTID IS NOT NULL AND A.MEASUREID IS NOT NULL
and exists (select 1 from J5C_MasterMeasures M
where M.StudentID = A.StudentID
and M.MeasureID = A.MeasureID)
Insert into J5C_MasterMeasures (studentid, measuredate, measureid, nce)
select A.studentid, A.measuredate, a.MEASUREID, A.score_10
from #GOOD_RECORDS3 a
join sysobjects so on so.name = 'J5C_Measures_Sys' AND so.type = 'u'
join syscolumns sc on so.id = sc.id and sc.name = 'score_10'
join [J5C_MeasureNamesV2_Sys] v on v.Score_field_id = sc.name
WHERE A.SCORE_10 IS NOT NULL AND A.STUDENTID IS NOT NULL AND A.MEASUREID IS NOT NULL
You have not menstioned the specifics of the unique constraint on J5C_MasterMeasures. Therefore, I assumed that all four columns being inserted were part of the constraint. In addition, your use of Except leads me to believe that you are using SQL Server 2005 or later. In addition, it is not clear how the join to J5C_MeasureNamesV2_Sys fits into the design or solution.
With GoodRecords As
(
Select A.StudentId
, A.measuredate
, B.measurename+ ' ' +B.LabelName
, A.score_10 As NCE
From [J5C_Measures_Sys] A
Join [J5C_ListBoxMeasures_Sys] B
On A.MeasureID = B.MeasureID
Where A.StudentId Is Not Null
And A.Score_10 Is Not Null
And A.MeasureId Is Not Null
Group By A.StudentId
, A.MeasureDate
, B.MeasureName+ ' ' +B.LabelName
, A.score_10
Having Count(A.Score_10) = 0
)
Insert J5C_MasterMeasures ( StudentId, MeasureData, MeasureId, NCE )
Select GR.StudentId, GR.MeasureData, GR.MeasureId, GR.NCE
From GoodRecords As GR
Join [J5C_MeasureNamesV2_Sys] v
On v.Score_field_id = 'Score_10'
Where Not Exists (
Select 1
From J5C_MasterMeasures As J1
Where J1.StudentId = GR.StudentId
And J1.MeasureData = GR.MeasureData
And J1.MeasureId = GR.MeasureId
And J1.NCE = GR.NCE
)